If you’re looking for this, you know why you need it. But just in case you’ve stumbled upon this and are curious, URL rewriting is useful for several reasons:
1. Accessibility: most people will rather remember a path that looks like http://www.example.com/products/shoes/12/ than http://www.example.com/index.php?category=products&type=shoes&productid=12
2. Security: granted, this is security through obscurity, but at the very least it will hide from most users the server-side technology used (PHP, ASP, etc) and the passed variable names
3. SEO compliance: Web crawlers work by following links and caching the content found; however, they don’t parse anything beyond the filename, so generally index.php?category=products, index.php?category=pages and index.php are seen as a single address, index.php. On the other hand, /products/, /pages/ and / are seen as 3 separate folders, and your content will thus be indexed correctly.
So, you’re thinking “Yes, that would be nice” (or alternatively, “Yeah yeah,get to the point already”). What do you need?
Well, first of all, your pages have to be hosted on an Apache server. Since over 50% of the servers in the world run on Apache, that shouldn’t be a problem.
Secondly, it should have mod_rewrite activated. This is a bit trickier; most hosts have it on by default, but you should probably check with your host.
Finally, a good grasp of regular expressions helps, but isn’t mandatory.
So, for basic URL rewriting, create a new file containing the following:
RewriteEngine On
RewriteRule ^$ index.php
RewriteRule ^([a-z0-9]+)(/)?$ index.php?page=$1 [NC]
This assumes, of course, that your paging is driven by a variable called page
Save this file as .htaccess
Please note that .htaccess is the actual extension of the file, the filename being blank. If you save it as, for instance, .htaccess.txt, it will not work.
Here, the first line activates mod_rewrite. The second line redirects all incoming requests to index.php. Finally, the last one takes any input, followed by a slash or not, case-insensitive, and redirects it to index.php?page=[the input]
You should however be careful with this, as a user with malicious intent might exploit this. Thus, in your code, you should sanitize all the inputs, or, in case you only have a few “main” pages (such as About, Tutorials, Links and Downloads, for instance) you could modify the last rule thus:
RewriteRule ^(about|tutorials|links|downloads)(/)?$ index.php?page=$1 [NC]
This can be further modified, adding whatever RegEx you need. So, you use our first example, you can write
RewriteRule ^([a-z0-9]+)/([a-z0-9]+)/([0-9]+)(/)?$ index.php?category=$1&type=$2&productid=$3 [NC]
I hope you found this useful
Update: For RegEx goodness, have a look at this article Mike Malone has posted: The absolute bare minimum every programmer should know about regular expressions