Browse By

Apache mod_rewrite Basics

Apache mod_rewrite is a tool that I wish I had tried to understand a lot early than I did. It makes URLs look so much cleaner not to mention the positive SEO results. This capability can take a URL that is common in PHP that looks like: http://www.yoursite.com/users.php?name=testuser&mod=settings and turn it into a URL that looks like: http://www.yoursite.com/users/testuser/settings.

The basics are fairly easy and straight forward. You will need to create a .htaccess file in the directory you want to format the URL. I always include in the first line of the file “RewriteEngine on”. You can use “RewriteEngine off” to disable blocks of rules so that you don’t have to comment them out or delete them from your .htaccess file. The RewriteRule directive uses Regular Expressions to match the URL typed to the URL you want.

Example:

RewriteEngine on
RewriteRule ^my/account([/]*)$ myacct.php
RewriteRule ^news/([0-9]+)$ news.php?id=$1

Explanation:

RewriteRule ^my/account([/]*)$ myacct.php: This rule looks for a URL starting and ending with “my/account” after the website, for instance http://www.yoursite.com/my/account and then changes it on the server side to be http://www.yoursite.com/myacct.php, but the user only sees http://www.yoursite.com/my/account.

RewriteRule ^news/([0-9]+)$ news.php?id=$1: This rule looks for a URL starting with “news” after the website. After “news” it looks for a number that corresponds with the id generated with the news posting. The “+” allows for one or more digit to be entered. For instance http://www.yoursite.com/news/1 would be changed on the serve to http://www.yoursite.com/news.php?id=1 , but the user only sees http://www.yoursite.com/news/1.

I hope this helps get you started. This is just a basic tutorial and there is so much more that can be done with Apache’s mod_rewrite feature. For more in depth information, check out these resources: