Articles » Mod rewrite Basics for SEOMod_rewrite is an Apache module. Mod_rewrite is a great way to make a websites URL's search engine friendly. The search engines don't like coming across a page with question marks in the href like 'index.php?page=home' and with mod_rewrite I will show you how that is possible.
This module can change a URL like 'www.somesite.com/news?page=4' to 'www.somesite.com/news/5/'. It is all server side so users will be none the wiser.
First things first
First you will need to know if mod_rewrite is on. To do this you can view your phpinfo page or create one. Create a page called phpinfo.php with the following code inside it and upload it to your server:
<?php phpinfo(); ?>
Load that page up in your web browser, and perform a search for “mod_rewrite”. All being well, you’ll find it in the “Apache loaded modules” section of the page. If it isn’t there, you’ll have to contact your hosting company and politely ask them to add it to the Apache configuration.
Creating an .htaccess fileTo start with we will need to create an .htaccess file and to do this just open something like notepad and save a file called .htaccess. The first line of code in the .htaccess file for mod_rewrite will be:
The .htaccess file has to be placed in the root of your website. Now the simple syntax for mod_rewrite basics is:
RewriteRule Pattern Substitution [OptionalFlags]
RewriteRule ^news$ /news/ [R] RewriteRule ^news/$ /news.php [L]
The pattern is the regular expression which is applied to the current URL, the substitution is the URL it will be redirected to or just redirected from. And the optional flags are [L] and [R] which are just 2 of the many flags. [L] is the last rule. No more rules will be processed if this one was successful. [R] is redirect. The user’s web browser will be visibly redirected to the substituted URL. The first line here adds a trailing slash if the user entered 'www.somesite.com/news' and the second line is the main part which is what makes 'www.somesite.com/news/' display the content of the news.php page. If you had $_GET variables set like 'www.somesite.com/news?page=4' we can easily rewrite this too:
RewriteRule ^news/([0-9]+)$ /news/$1/ [R] RewriteRule ^news/([0-9]+)/$ /news.php?page=$1 [L]
Again the first line is for adding a trailing slash. ([0-9]+) is a regular expression which checks for any amount of integers within the brackets. Because the page is only redirecting from news.php?page=1 you can still use your php GET variables. If you want to know more about regular expressions go to http://www.zytrax.com/tech/web/regex.htm as there is a lot to know and that would mean another article!
Apaches big page on mod_rewrite: