Manipulating URLs with Apache Mod Rewrite
Tutorial on how to enable and use the mod_rewrite module of Apache. And how to rewrite your dynamic URLs, into search engine friendly URLs.
Mod Rewrite is a Module for Apache made in April 1996, which allows the use of regular expressions, to rewrite requested urls.
There are many good reasons to make use of mod-rewrite, one of the best being, that you can avoid using URL parameters, by having a rewriting system in place.
How to Enable Mod_Rewrite with Apache
Some servers don't have mod_rewrite enabled by default, if you just finished installing Apache, then its likely that you need to uncomment the below line in httpd.conf
#LoadModule rewrite_module modules/mod_rewrite.so
You simply need to remove the number symbol (#) in front of the line.
Not Running your own Server?
If you host your site with a shared hosting provider, then you should make sure that they have Mod_Rewrite enabled, as you may not have access to enable it on your own.
How it works
The below example will redirect URLs from the Articles/NUMBER/, to the real URLs. This redirect happens on the server, and the user wont notice anything.
RewriteEngine on RewriteRule ^Articles/([0-9]+)/$ /?AID=$1
First i enabled the RewriteEngine by setting it to "on", next i typed in my rewrite rule, which is a simple regular expression.
The Regular Expression
Take the below.
^Articles/([0-9]+)/$ /?ARTICLE=$1
The ([0-9]+) part tells that the numbers 0-9 are allowed, and the following plus sign (+) tells that one or more is allowed, finally the parentheses is used to remember the content, this can later be accessed through the variable "$1", which will be used to pass the number on to the real URL. Basically this tells the server to rewrite the below root-relative URLs.
/Articles/NUMBER/
Into the following (root relative).
/?ARTICLE=$1
If you dont understand what i mean about root relative, then you should also read Absolute and Relative Paths.
Problems
One problem which is likely to be common for beginners, is broken URLs for their external stylesheets, and/or images. Mod_rewrite and relative paths, are known to cause problems, the solution is either to use absolute paths, or root relative paths. You should read Absolute and Relative Paths for more information.