So lets get started...
What is Mod Rewrite?
Mod rewrite is a part of apache servers that can rewrite requested URLs on the fly. As it supports an endless number of rules that in turn have unlimited attached rule conditions it is very flexible and an important URL manipulation mechanism. It can be used for internet users and for search engine friendly URLs. This increases the chance of the database driven website to be indexed. Which is a very good thing for you and your website.
Enabling / Installing Mod Rewrite
The first thing we want to do is make sure that we have mod_rewrite on our server. By default, Apache has mod_rewrite installed, but not enabled. The easiest way to test if mod_rewrite is enabled on your server is to create a .htaccess file in a test directory such as /modrewrite-test/.htaccess and edit it to look like this:
Options +FollowSymLinks
RewriteEngine On
Now to test, attempt to browse to the subdirectory(test). One of two things could happen:
- No errors mod_rewrite engine is now enabled.
- 500, Internal Server Error If you get this message then mod_rewrite was not installed or enabled on your server
- Find the httpd.conf file (usually you will find it in a folder called conf, config or something along those lines)
- Inside the httpd.conf file uncomment the line LoadModule rewrite_module modules/mod_rewrite.so (remove the pound '#' sign from in front of the line)
- Also find the line ClearModuleList is uncommented then find and make sure that the line AddModule mod_rewrite.c is not commented out.
/etc/init.d/httpd restart
Using Mod Rewrite To Always Remove / And Add WWW
At the top of any .htaccess file, you need to turn Mod Rewrite on. This should always be at the top of your .htaccess file.(You only need to turn Mod Rewrite on once)
RewriteEngine On
RewriteBase /
To always add the www to the front of your site, add the following to your .htaccess file located in the root dir(/):
RewriteCond %{HTTP_HOST} ^yoursite.com$
RewriteRule (.*) http://www.yoursite.com$1 [R=301]
