SEO Your Application With mod_rewrite
Generally speaking, many search engines like Google, MSN, and Yahoo like to see your URLs be as pretty as possible. Using applications like PHP will often produce URLs that look like this: http://somesite.com/index.php?section=section1&data=test. These URLs are typically frowned upon by the search engines and can produce mixed results when attempting to achieve the highest search engine ranking.
There are two methods we can use to make our URL’s a bit more friendly. Many applications today already provide pre-packaged .htaccess files. It’s important for me to explain that there are two methods for setting up mod_rewrite rules. The first (and most common) method is to use a file called “.htaccess” placed in the root directory of your web site. This file is read in to the Apache configuration in real time (The AllowOverride option in your Apache configuration controls this). We’ll cover the .htaccess method here.
The .htaccess Method
This is the most common way to implement mod_rewrite rules. First, open a text file with your favorite editor (if you do not have shell access simply use notepad or vi on your local machine). Remember that a dot (.) before the file name designates this file as hidden in Linux.
For our example we’re going to redirect http://somesite.com/index.php?section=section1&data=test to look like this: http://somesite.com/section1/test.
- Edit the .htaccess file you wish to
# vi /var/www/html/.htaccess
- Place the following in the new .htaccess file:
RewriteRule ([^/]+)/([^/]+)?$ index\.php?section=$1&data=$2 [L]
- Save the file and exit your editor.
(* Note: If you upload this file with an FTP/SCP program your file will not appear as it is hidden, if you need to delete the file due to a misconfiguration, issue “DELE .htaccess” in the directory you uploaded the file.)
The [L] directive tells mod_rewrite to redirect the request with a 301 redirect.
- I receive a 500 server error after uploading.
Check to make sure no typo’s were made. Check the apache error_log for any clues.
- The redirect does not take place but the site still shows.
This is usually because your host does not support mod_rewrite or is not allowing .htaccess files. To check if .htaccess is being parsed open a new .htaccess and put the following inside:
Redirect /test “http://www.google.com”
If this works you can safely assume that .htaccess files are being parsed.