On almost every Apache server you will find different plugins and tools you can work with. One of these modules is mod_rewrite which allows you to redirect URLs according to matched regular expressions. These can range from extremely simple commands to very complex lines of code. The URL rewriting scheme is perfect for web developers trying to customize their site.

In this tutorial I’ll introduce a few commands that beginners can start with right away. All you need is Apache, which you can install on your local machine or work off a remote server.

How Does it Work?

When a visitor first requests your webpage it’ll connect to your online web host. This server then looks for a file named .htaccess which is basically a hidden configuration file.

In here we can write a whole set of rules to match for whenever a visitor is requesting a URL. Then using the Apache mod_rewrite module it’s possible to redirect their requests behind-the-scenes and create the illusion of “pretty URLs”. As an example let’s look at the two following URL schemes:

# http://www.example.com/blog/1181/
# http://www.example.com/blog.php?type=post&id=1181

These are two completely valid URLs which could be matched on your website. The first example is much easier to recognize and share on other websites, while the second targets a specific script file(blog.php) and appends some post data. Let’s look into how we could redirect this using an .htaccess file.

Setting Up the Server

When first creating your file we need to include some standard rules. These will setup the server environment and allow for http traffic to be redirected. Include these few lines at the top of your new .htaccess file:

AddDefaultCharset UTF-8
RewriteEngine on
RewriteBase /

We first set the character type as UTF-8 so there aren’t any parsing issues. RewriteEngine on is probably the most important line you must include. This lets Apache know we need to use the mod_rewrite functionality and is required for any rewrite rule statement. Additionally I’ve included the RewriteBase statement setting our remote directory to the root folder.

This should be changed if your application is running within another directory. For example, I setup my addon domains in a file structure such as /public_html/domains/mydomain.com. When creating an .htaccess file in this folder I would reset the config to RewriteBase /domains/mydomain.com/.

Making Pretty URL Schemes

With the configuration settings in place we can look into changing up the URL structure. I’m going to use the same example I pointed out earlier and direct to a similar page. First take a peek at the line of code below:

RewriteRule ^blog/([0-9]+)/?$ blog.php?type=post&id=$1 [L]

There’s a lot to understand here so we can break it down piece-by-piece. The segment enclosed within ^ and $ are the rules to be matched. This means we need to match a URL structure starting with /blog/ and followed by a set of numbers 0-9. The + sign means we can have more than one number, possibly unlimited! Then finally we have a closing forward slash with a question mark, imposing this is optional(ie. /blog/1181 will work).

Now the latter piece of the rewrite rule contains our behind the scenes redirect. In this case we are targeting a file called blog.php located in the document root. We already know the type of content is a post, but we do not know the post ID yet. This is why we can set it dynamically with the $1 variable.

Every time you open a set of parentheses this creates a new match rule. You can open many of these in a single URL, but in this case we only have one which happens to be our post ID number. If you create more match variables you can reference them in numerical order like $2, $3, etc.

Understanding Flags

Another bit I should explain is the use of flags. These can be found in brackets at the end of your rewrite line. In the example above we are using the [L] flag which means the Last flag. This will force Apache will stop looking for other rules once it matches this one.

I highly recommend this online cheat sheet as a mod_rewrite syntax guide. It has a table listing of all the possible flags you can include in your rewrite rules. Additionally there are flags & operators you can use inside the regular expression. These rules will take months to memorize, so having a bookmark like this will come in handy quite often.

Directing www and non-www Traffic

Another classic trick to custom URLs is the www subdomain. When you purchase a domain name it does not automatically disable or enable the root www subdomain which is typical of the modern Internet. Generally both the URLs will work at first – however it’s bad practice to leave both of them open.

Google and other Search Engines really like when you specify one or the other. If all your backlinks point towards either www or non-www traffic then it should work out okay. But instead we should use .htaccess rules to always direct traffic either towards www or non-www. Check out my example code below directing all traffic to non-www:

RewriteCond %{HTTP_HOST} ^www\.dzineblog\.com$ [NC]
RewriteRule ^(.+)$ http://dzineblog.com/$1 [R=301,L]

This will check if the user is coming in from the www subdomain and redirect to the standard URL instead. You can switch it up so that all users coming in from the regular URL are instead directed to the www subdomain every time. Notice that all the rest of the URI (/blog/whatever/) is always appended back onto the redirected domain.

RewriteCond %{HTTP_HOST} !^www\.dzineblog\.com [NC]
RewriteRule (.*) http://dzineblog.com/$1 [R=301,L]

This new rule above will check the HTTP request and only pulls a match if the domain does NOT have a www attached. If that is the case the whole URL is directed towards the www subdomain and continues along just fine. You can directly copy/paste either of these codes into your own file and change the domain name to reflect yours. It should work perfectly every time you access the website.

Related Readings

  1. mod_rewrite Cheat Sheet (V2)
  2. Ultimate Guide to htaccess and mod_rewrite
  3. How to use mod_rewrite to create clean URLs
  4. More .htaccess mod_rewrite examples
  5. Redirecting and Remapping with mod_rewrite – Apache Docs
  6. URL Rewriting – Redirecting URLs with Apache’s mod_rewrite


I hope this introduction to .htaccess rewrites hasn’t been too confusing. There is a lot to understand and you won’t be able to process all of this syntax with just a few hours time. But try following along with the examples above and possibly build a practice file for yourself.

URL routing schemes are extremely important to any web application. Consider all of the different user profile pages, story submissions, and blog posts to be found online. Your website should be just as easy to navigate and share around to your friends & family. If you have ideas or suggestions for coding rewrite rules in .htaccess feel free to share with us in the post discussion area.

Posted by Jake Rocheleau

Jake is a writer & digital designer/illustrator. He writes about all things web and creative. Check out his website for work samples and follow his latest updates on Twitter @jakerocheleau.

Leave a reply

Your email address will not be published. Required fields are marked *