URL rewriting examples
1) Rewriting product.php?id=12 to product-12.html
RewriteEngine on
RewriteRule ^product-([0-9]+).html$ product.php?id=$1
2) Rewriting product.php?id=12 to product/ipod-nano/12.html
RewriteEngine on
RewriteRule ^product/([a-zA-Z0-9_-]+)/([0-9]+).html$ product.php?id=$2
3) Rewriting yoursite.com/user.php?username=xyz to yoursite.com/xyz
RewriteEngine On
RewriteRule ^([a-zA-Z0-9_-]+)$ user.php?username=$1
RewriteRule ^([a-zA-Z0-9_-]+)/$ user.php?username=$1
Tricks to write
Beginning rewriting..
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 |
---------------------------------------------------------------
Important: While some of the directives on this page may appear split onto two lines in your browser, in your .htaccess file they must exist completely on one line. If you drag-select and copy the directives on this page, they should paste just fine into any text editor
all requests to whatever.htm will be sent to whatever.php:
---------------------------------------------------------------
| Options +FollowSymlinks |
| RewriteEngine on |
| RewriteRule ^(.*).htm$ $1.php [NC] |
---------------------------------------------------------------
not-so-simple rewriting ... flat links and more
Even a cute short link like http://mysite/grab?file=my.zip is too ugly for some people, and nothing less than a true old-school solid domain/path/flat/link will do. Fortunately, mod_rewrite makes it easy to convert URLs with query strings and multiple variables into exactly this, 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 this link as..
http://mysite/files/games/hoopy.zip
and in the background have that transparently translated, server-side, to..
http://mysite/download.php?section=games&file=hoopy