Mod_Rewrite is a Module for the Apache HTTP server, which allows the use of regular expressions to create rules to "rewrite" requested URLs on-the-fly. By "rewrite" is really meant, if a the pattern of a given rule matches a HTTP request, it will typically be silently directed to a script on the server, which will then respond with the content that was requested.
There are many benefits from using mod-rewrite. One of the better benefits, is that you can avoid using URL parameters, and that your URLs are more human and search-engine friendly. In practice however, people rarely remember URLs anyway, so it is mostly for the sake of search engines.
How to Enable Mod_Rewrite with Apache
Some servers do not have mod_rewrite enabled by default. This can be the case if you only just finished installing Apache. How to enable mod_rewrite depends on your operating system, and possibly which version of Apache you are using. Traditionally you would often just 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.
On Linux you can typically enable everything from the terminal, which can be done by entering the following commands:
sudo a2enmod rewrite && sudo service apache2 restart
The above commands is really two commands written into a single line. As with most other maintenance and update tasks on linux, the "sudo" command is very important, as it grants the necessary root privileges that are required to execute the command properly.
Writing rewrite rules for mod_rewrite
The below example will redirect all URLs matching the Articles/NUMBER/ pattern, to the file located at the root (/) location of our domain – typically index.php – which we want handling all requests. 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", this step is necessary for our rewrite rules to work. Next typed a rewrite rule, which is basically regular expression.
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.
Into the following (root relative).
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.