One of the more powerful tricks of the .htaccess hacker is the ability to rewrite URLs. This enables us to do some mighty manipulations on our links; useful stuff like transforming very long URL’s into short, cute URLs, transforming dynamic ?generated=page&URL’s into /friendly/flat/links, redirect missing pages, preventing hot-linking, performing automatic language translation, and much, much more.
Whenever you use mod_rewrite (the part of apache that does all this magic), you need to do:
you only need to do this once per .htaccess file:
Options +FollowSymlinks
RewriteEngine on
..before any ReWrite rules. note: +FollowSymLinks must be enabled for any rules to work, this is a security requirement of the rewrite engine. Normally it’s enabled in the root and you shouldn’t have to add it, but it doesn’t hurt to do so, and I’ll insert it into all the examples on this page, just in case*.
Simple Rewritting
Simply put, Apache scans all incoming URL requests, checks for matches in our .htaccess file and rewrites those matching URLs to whatever we specify. something like this..
All requests to whatever.htm will be sent to whatever.php
Options +FollowSymlinks
RewriteEngine on
RewriteRule ^(.*)\.htm$ $1.php [nc]
This will do a “real” http redirection:
Options +FollowSymlinks
RewriteEngine on
RewriteRule ^(.+)\.htm$ http://corz.org/$1.php [r=301,nc]
This time we instruct mod_rewrite to send a proper HTTP “permanently moved” redirection, aka; “301″. Now, instead of just redirecting on-the-fly, the user’s browser is physically redirected to a new URL, and whatever.php appears in their browser’s address bar, and search engines and other spidering entities will automatically update their links to the .php versions; everyone wins. and you can take your time with the updating, too.
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
shortening URLs
One common use of mod_rewrite is to shorten URL’s. shorter URL’s are easier to remember and, of course, easier to type. an example..
beware the regular expression:
Options +FollowSymlinks
RewriteEngine On
RewriteRule ^grab(.*) /public/files/download/download.php$1
this rule would transform this user’s URL..
http://mysite/grab?file=my.zip
server-side, into..
http://mysite/public/files/download/download.php?file=my.zip