Hoe doe ik Short url rewrite rules met htaccess
Inleiding
Hoe gebruik ik htaccess om de url zo mooi mogelijk te maken. We hebben een paar voorbeelden opgesomd: |
Stappen
all requests to whatever.htm will be sent to whatever.php:
Options +FollowSymlinks RewriteEngine on RewriteRule ^(.*)\.htm$ $1.php [nc]
Handy for anyone updating a site from static htm (you could use .html, or .htm(.*), .htm?, etc) to dynamic php pages; requests to the old pages are automatically rewritten to our new urls. no one notices a thing, visitors and search engines can access your content either way. leave the rule in; as an added bonus, this enables us to easily split php code and its included html structures into two separate files, a nice idea; makes editing and updating a breeze. The [nc] part at the end means "No Case", or "case-insensitive", but we'll get to the switches later.
Folks can link to whatever.htm or whatever.php, but they always get whatever.php in their browser, and this works even if whatever.htm doesn't exist! but I'm straying..
As it stands, it's a bit tricky; folks will still have whatever.htm in their browser address bar, and will still keep bookmarking your old .htm URL's. Search engines, too, will keep on indexing your links as .htm, some have even argued that serving up the same content from two different places could have you penalized by the search engines. This may or not bother you, but if it does, mod_rewrite can do some more magic..
this will do a "real" http redirection:
Options +FollowSymlinks rewriteengine on rewriterule ^(.+)\.htm$ http://corz.org/$1.php [r=301,nc]
You may have noticed, the above examples use regular expression to match variables. what that simply means is.. match the part inside (.+) and use it to construct "$1" in the new URL. in other words, (.+) = $1 you could have multiple (.+) parts and for each, mod_rewrite automatically creates a matching $1, $2, $3, etc, in your target URL, something like..
a more complex rewrite rule:
Options +FollowSymlinks RewriteEngine on RewriteRule ^files/(.+)/(.+).zip download.php?section=$1&file=$2 [nc]
would allow you to present a link as..
http://mysite/files/games/hoopy.zip
and in the background have that translated to..
http://mysite/download.php?section=games&file=hoopy
lose the "www" I'm often asked how I prevent the "www" part showing up at my site, so I guess I should add something about that. Briefly, if someone types http://www.corz.org/ into their browser (or uses the www part for any link at corz.org) it is redirected to the plain, rather neat, http://corz.org/ version. This is very simple to achieve, like this..
beware the regular expression:
Options +FollowSymlinks RewriteEngine on rewritecond %{http_host} ^www\.corz\.org [nc] rewriterule ^(.*)$ http://corz.org/$1 [r=301,nc]