Noupe Editorial Team August 18th, 2009

10+ Mod_Rewrite Rules You Should Know

Mod_rewrite is an Apache-based rewrite engine for dynamically rewriting URLs. It's built into Apache servers natively, though not enabled by default. It's capable of functions beyond simple rewrites, though, some of which are included below.

Mod_Rewrite Rules You Should Know

Internet's universe... photo by CLUC shared under Attribution-NonCommercial-NoDerivs 2.0 Generic (CC BY-NC-ND 2.0) licence

Turn Mod_Rewrite On

Mod_rewrite is used through your .htaccess file. Place the following code at the beginning of your .htaccess file to turn mod_rewrite on:
RewriteEngine on
(Don't forget that .htaccess commands are case-sensitive.) This code needs to be entered at the beginning of any .htaccess file using mod_rewrite.

The Basic Mod_Rewrite Layout

The basic format for a mod_rewrite command is:
RewriteRule Pattern Substitution [Flag(s)]

URLs are Always Relative

The URL you redirect to is always relative to the directory in which your .htaccess file is placed. So if it's in the root directory, URLs are all in relation to the root directory; if it's in a sudirectory, URLs are in relation to that particular subdirectory.

A Basic Redirect

If you just want to create a simple 301 redirect from one URL to another, then use the following code:
RewriteRule ^fileone.html$ filetwo.html
This is a very basic rule that means any requests for fileone.html will be sent to filetwo.html.

Require no "www"

This bit of code will make it so visitors to your site don't need to type in the "www" bit of your website address.
RewriteCond %{HTTP_HOST} !^domain.com$ [NC]
RewriteRule ^(.*)$ http://domain.com/$1 [R=301,L]

Block a Specific IP Address

If you want to block someone coming from a specific IP address from accessing your website, you can use the following code:
RewriteCond %{REMOTE_ADDR} ^(A.B.C.D)$
RewriteRule ^/* http://www.domain.com/sorry.html [L]
Replace the A.B.C.D with the IP address you want to block (don't forget to leave the "" before each dot, which escapes the character).

Block Specific User Agents

If you want to block a group of IP addresses using the same User Agent (bot), the following code with do it:
RewriteCond %{HTTP_USER_AGENT} UserAgent
RewriteRule .* - [F,L]
Just replace the "UserAgent" bit with whatever user agent you want to block. You can also block more than one at a time by replacing the top line in that code with something like this:
RewriteCond %{HTTP_USER_AGENT} UserAgentA [OR]
RewriteCond %{HTTP_USER_AGENT} UserAgentB
You can put as many user agents in as you want, just make sure you end each line with [OR] (with the exception of the last line, of course).

Strip Query Strings

Let's say all the pages on your site other than your home page are formatted as follows, with query strings instead of page names: http://www.domain.com/home.html?example=12345abcd Those aren't very pretty, and on top of that, search engines will show a bunch of duplicated "home" pages. If you want to get rid of the query string in your page URLs, use the following code:
RewriteCond %{QUERY_STRING} example=
RewriteRule (.*) http://www.domain.com/$1? [R=301]
This not only gets rid of the query string, but also the preceding question mark.

Set up a Default Image

Using a default, backup image in case of broken images can make your site look more professional. Use the following code to redirect to a default image for any image whose file cannot be found.
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^images/.*.jpg$ /images/default.jpg [L]
Of course, you can change the ".jpg" bit to whatever file type you're using. Make sure you have an image called "default.jpg" or change that to whatever your default image filename is.

Prevent Hotlinking

The last thing most website owners want is other sites stealing their content or worse—hotlinking to their images and stealing their bandwidth. Here's a simple bit of code that prevents it:
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http://(www.)?domain.com/ .*$ [NC]
RewriteRule .(gif|jpg|swf|flv|png)$ /feed/ [R=302,L]
Make sure you change the "domain.com" bit to your own domain name.

Redirect to a Maintenance Page

If you need to take your entire site offline for a bit and redirect to a maintenance page (or some other page), use the following code:
RedirectMatch 302 ^/ /maintenancepage.html
Change the "maintenancepage.html" bit to wherever your maintenance page file is located.

Redirect Multiple Domains to a Single Domain

If you have multiple domains pointing to your site, it's possible you could take a hit in the search engines for having duplicate content. Use the following code to redirect visitors from two domains to just one:
RewriteCond %{HTTP_HOST} ^www.domain.net$ [NC,OR]
RewriteCond %{HTTP_HOST} ^domain.net$ [NC,OR]
RewriteCond %{HTTP_HOST} ^www.domain.net$ [NC]
RewriteRule ^(.*)$ http://domain.net/$1 [R=301,L]

Remember the Filesystem Always Takes Precedence

The filesystem on your server will always take precedence over the rewritten URL. For example, if you have a directory named "services" and within that directory is a file called "design.html", you can't have the URL redirect to "http://domain.com/services". What happens is that Apache goes into the "services" directory and doesn't see the rewrite instructions. To fix this, simply rename your directory (adding an underscore to the beginning or end is a simple way to do that).

Remember:

  • Because mod_rewrite works within the .htaccess file, commands are case sensitive.
  • Always back up your .htaccess file before making any changes to it. This way, if there's a problem, you can easily restore your site.

More Resources:

Author: Cameron Chapman

Cameron Chapman is a writer, blogger, copyeditor, and social media addict. She's been designing for more than six years and writing her whole life. If you’d like to connect with her, you can follow her on Twitter or at her Personal Website.
Write for Us! We are looking for exciting and creative articles, if you want to contribute, just send us an email.

Noupe Editorial Team

The jungle is alive: Be it a collaboration between two or more authors or an article by an author not contributing regularly. In these cases you find the Noupe Editorial Team as the ones who made it. Guest authors get their own little bio boxes below the article, so watch out for these.

61 comments

  1. If i have a page like this “www.yoursite.com/game.php?id=123” and I want to show the url as “www.yoursite.com/game/123” what should I write? Can anyone email me?

    There are several pages in this domain which I want same kind of redirection. Whats the method?

    1. @Sourav:
      Here you go:
      1) For Single URL
      Options +FollowSymLinks
      RewriteEngine on

      RewriteRule game-id-(.*)\.php game.php?id=$1
      Result: http://www.yoursite.com/game-id-123.php

      2) For Directory Separated URL:
      Options +FollowSymLinks
      RewriteEngine on

      RewriteRule game/id/(.*) game.php?id=$1
      Result: http://www.yoursite.com/game/id/123/

      3) For Comma Separated URL:
      Options +FollowSymLinks
      RewriteEngine on

      RewriteRule game,(.*)\.php game.php?id=$1
      Result: http://www.yoursite.com/game,123.php

      I found a web site where you can generate rewrite commands (very limited though). more on http://rapid.searchmetrics.com/en/seo-tools/miscellaneous/url-rewrite,44.html

  2. I’ve truly appreciated reading your articles. You obviously know what you are talking about! Your internet site is so effortless to navigate as well, I’ve bookmarked it in my favourites :-D

  3. Thank you for this article, it really helped to stop an iPhone developer from harvesting the latest lottery numbers from our website at http://www.alottery.com each time a user accessed their app – up until now it has been eating almost 2Gb a month in bandwidth.
    Keep up the good work, love the site!

  4. I need a little help. Every day I find some visitors using Googlebot as their browser’s User Agent while visiting my site. I want to stop the fake Googlebots. How can I allow the real ones and keep out the fake ones? Is there any way to do this via htaccess?

  5. Helpful tutorial, thx for the explanation, by the way I’m stuck on redirecting Html/php sample pages with no DB to .Aspx/.pl/.do or any other extension :S

    Example:
    website.com/index.php or index.html
    to: website.com/index.do or any other perfect extension
    Please help me to rewrite rules on the file .htaccess

    (!) You can also keep in touch with me or email me at: [email protected]

  6. wow very nice article it helps me a lot iam now removing all the query string in my website i was told it will help me rank in search engines muhammed sekertekin

Leave a Reply

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