Use the links below to share Beyond Redirect: Using ReWriteRule in .htaccess on your favorite social networks.

Back to the Article >>

Beyond Redirect: Using ReWriteRule in .htaccess

June 30th, 2008 in Programming & IT

by: Matthew Griffin

Mod_rewrite is an Apache module that can be accessed from .htaccess files to perform all kinds of complicated URL manipulation. A few months ago I posted an article called Beat Your Website into Submission with .htaccess explaining how to use several .htaccess features to do helpful tricks; but I didn't really touch on mod_rewrite or RewriteRule. Since then I was involved in a project that required extensive use of mod_rewrite and I've come to truly appreciate its power and usefulness. The main mod_rewrite function, RewriteRule, is powered by regular expressions. Regular expressions are used to search blocks of text for specific patterns. I barely have enough room in this article to scratch the surface of regular expressions; so if you need more detail in that area I recommend this website. For the purposes of this tutorial, though, I'll be sticking to commonly used URL rewriting tasks.

The Setup

Before you start messing with RewriteRule, you need to make sure your .htaccess file is ready for tinkering. The first two lines in the sample code below activate the mod_rewrite module. The third line prevents more than ten redirects per browser call. If this line is left out, a misplaced "+" or "." in your regular expression could create an infinite loop that will grind your server to a halt. Unfortunately, I didn't discover this little snippet until I was about half way through my project. But you can avoid my mistake. Put this at the top of your .htaccess file.

Options +FollowSymlinks
RewriteEngine on
RewriteOptions MaxRedirects=10

RewriteRule Basics

With mod_rewrite there are a number of powerful functions at your disposal. You saw RewriteEngine and RewriteOptions in the first section. These functions set the stage for the star of the show—RewriteRule. RewriteRule can compare a URL against just able any criteria and rewrite the url according to your specifications. As I mentioned, RewriteRule uses regular expressions to search a URL for character patterns. Here's a helpful example that matches any URL that ends with .htm and redirects it to the same file with the extension .php. This would be helpful if you were moving your website from a static HTML site to a PHP driven site.

Options +FollowSymlinks
RewriteEngine on
RewriteOptions MaxRedirects=10
RewriteRule ^(.*).htm$ $1.php [NC]

On the RewriteRule line the "^" denotes the beginning of the regular expression and the "$" denotes the end. The [NC] at the end of the RewriteRule line keeps the command from being case-sensitive.

Redirecting the Right Way

Lots of web designers know that .htaccess can be used to redirect a browser to another page. But very few know much beyond the absolute basics and even fewer know the right code to send with the redirect. For search engine purposes it's important that you don't get these codes mixed up. All of the redirect codes are in the 300 range. W3.org has an extensive guide to redirect codes but here are the ones most commonly used:

301 Permanently Moved
Use this code when you have content that has permanently moved to a new URL.
302 Found
Use this code when you have content that is temporarily residing at a different URL.
307
The same as 302 with some additional options

Redirecting Your Website to a New Domain

Whenever you change the domain of your website, it's important to redirect properly to the new domain name to avoid a double content penalty from search engines. For example, if you simply park your old domain on top of your new domain, some search engines will see this as double content. Here's a RewriteRule that will redirect correctly with a 301 (Permanently Moved) code.

Options +FollowSymlinks
RewriteEngine on
RewriteOptions MaxRedirects=10
RewriteRule ^(.+).php$ http://new_domain.com/$1.php [R=301,NC]

Sometime, when you move a website to a new domain, the names of the pages don't necessarily stay the same. To redirect a page on one domain to a page with a different name on a new domain, you would add an additional ReWriteRule line to your .htaccess file that would look like this:

RewriteRule ^old_page.php$ http://new_domain.com/new_page.php [R=301,NC]

Creating Dynamic Directories in the Root of Your Site

The RewriteRule will parse the URL request as it comes in from the browser...

Lots of social sites such as MySpace.com allow you to access certain personal pages in a url format that looks like this: myspace.com/myusername. Obviously, MySpace doesn't manually create a new directory every time a new member joins. Achieving this effect is simple with RewriteRule. But in order to make this example work, all of the pages in your website will need to be moved into a new directory in the root of your site (eg. mydomain.com/pages). There should be no pages in the root directory of the site at all. The RewriteRule will parse the URL request as it comes in from the browser and redirect accordingly. The code below will search an incoming URL for a simple user name that is between 6 and 12 characters long. If no user name is present, the browser will be redirected to the index.php page in the "pages" directory. A second .htaccess file (listed after the one below) should be created and uploaded into the "pages" directory. This .htaccess file will block the RewriteRules from the first .htaccess files.

Options +FollowSymlinks
RewriteEngine on
RewriteOptions MaxRedirects=10

RewriteRule ^(.{6,12})$ http://mydomain.com/pages/users/index.php?user_name=$1 [NC]
RewriteRule ^$ http://mydomain.com/pages/index.php [R=301,NC]

The first RewriteRule redirects any URL with a six to twelve character user name to the the user page and passes the user name in as a variable. The second RewriteRule checks for incoming URLs that have no user name (ie. http://mydomain.com/). When this occurs, the visitor is redirected to the home page in the "pages" directory. This is the .htaccess file that should be placed in the "pages" directory.

Options +FollowSymlinks
RewriteEngine off

Beautifying and Optimizing Your URLs

Long URLs with multiple embedded variables are ugly, awkward to copy and paste, and difficult for search engines to index. With RewriteRule, though, you can turn a URL that looks like this: http://mydomain.com/blog.php?category=news&month=05&year=2008 into this: http://mydomain.com/news/05/2008. Much more attractive, right? Here's the code:

Options +FollowSymlinks
RewriteEngine on
RewriteOptions MaxRedirects=10

RewriteRule ^blog/([^/]+)/([^/]+)$ blog.php?category=$1&article_id=$2 [NC]

In this example, matches found in parenthesis are stored in successive variables starting with $1 and going up. So, for example the URL http://mydomain.com/blog/news/4450 would be rewritten http://mydomain.com/blog.php?category_id=news&article_id=4450.

  • 64 Comments
  • 50042 Views

Back to the Article >>