Getting Started With mod_rewrite

Monday, September 5th, 2011 | .htaccess | 0 comments

What is mod_rewrite?

First of all, let’s get things straight: mod_rewrite is your friend. It is also an Apache module that rewrites URL’s at the server level. If you’re reading this, I’m going to assume you’ve already enabled mod_rewrite on your server. If not, there’s plenty of tutorials to show you how to enable it. All set? Okay, let’s go!

Simple mod_rewrite Example

We’ll be starting with a simple mod_rewrite example just to get your feet wet. All rewrite rules follow a particular structure: RewriteRule Pattern Substitution [OptionalFlags]
This example will redirect http://www.example.com/foo.html to http://www.example.com/bar.html. This can be accomplished by creating an .htaccess file and inserting the following:

<?php
RewriteEngine on
RewriteRule ^foo.html$ bar.html
?>

Visiting http://www.example.com/foo.html will now redirect you to http://www.example.com/bar.html. However, notice that the URL still displays foo.html. If you’d prefer the browser to visibly redirect to the new page, you’ll need to make a couple changes to your .htaccess file:

<?php
RewriteEngine on
RewriteRule ^foo.html$ http://www.example.com/bar.html [R]
?>

You’ll notice that I’ve added an [R] flag to the end of the rewrite rule. This tells the browser to visibly redirect to the new page. Also, I had to write out the full URL of the page that I’m redirecting to. If the page you’re redirecting to happens to fall within the root directory of the same site, you can simply write /page.html instead of the full URL.

Fancy Schmancy Redirect

This example is going to show you how to make your URL’s pretty. I’m talking prettier than Halle Berry. Let’s start off with an example:

<?php
RewriteEngine On
RewriteRule ^([^/\.]+)/([^/\.]+)/?$ index.php?category=$1&product=$2 [L]
?>

With a rewrite rule like this in place, http://www.example.com/nestle/quik effectively redirects to http://www.example.com/index.php?category=nestle&product=quik. I’m going to break this rewrite rule out into multiple parts, seeing how it’s a bit more complicated than the first example:

  1. ^([^/\.]+)/([^/\.]+)/?$ – This pattern returns two variables, separated by a forward-slash. The two variables can contain any characters that aren’t a forward-slash or a period.
  2. $1.php – This is the page that you’ll be redirected to. $1 and $2 will be replaced with the previously captured data, respectively.
  3. [L] – This optional flag tells Apache to stop processing rewrite rules after this point.

Well, I hope this wasn’t too overwhelming. This is just scratching the surface of mod_rewrite. Remember though, once you’ve got mod_rewrite down, all the ladies will constantly swarm you. Okay, that might not be true, but it will definitely save you a few headaches.

 

Heyyyyy, Leave A Comment!

Submit