MOD_REWRITE tips and tricks

Before you begin to use mod_rewrite (RewriteRule, RewriteBase, and RewriteCond) code, keep in mind that each rule applied is executed on each and every HTTP request that accesses a file in or below the directory where the code resides.

A work-around is to is to limit the code to certain circumstances (if readily identifiable). For instance, to limit the next 3 RewriteRules to only be applied to .html and .php files, you can use the following code, which tests if the url does not end in .html or .php and if it doesn’t, it will skip the next 5 RewriteRules.

RewriteRule !.(html|php)$ - [S=3]
  • Always begin .htaccess rewrites with:
RewriteEngine On RewriteBase /
  • Make sure that +FollowSymLinks is added to your Options. It will force the server to follow all links.
Options +FollowSymLinks

Require the WWW

Note: [NC] means not case sensative. [R=301] action means a permanent redirect. A [R=302] means a temporary. Choose the most appropriate.

Options +FollowSymLinks
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} !^www\.yoursite\.com$ [NC]
RewriteRule ^(.*)$ /$1 [R=301,L]

Non WWW url to WWW.yoursite.com

Options +FollowSymLinks
RewriteEngine On
RewriteBase /
# non www to www.yoursite.com and follow all links
RewriteCond %{HTTP_HOST} ^yoursite\.com$ [NC]
RewriteRule ^(.*)$ http://www.yoursite.com/$1 [R=301,L]

External Redirect .php files to .html files (SEO friendly)

RewriteRule ^(.*)\.php$ /$1.html [R=301,L]

Internal Redirect .php files to .html files (SEO friendly)

Redirects all files that end in .html to be served from filename.php so it looks like all your pages are .html but really they are .php

RewriteRule ^(.*)\.html$ $1.php [R=301,L]

Redirecting entire sites with 301

The 301 directive is quite powerful. You can redirect not just single files but entire sites, for example when changing domain names e.g.

redirect 301 / http://www.yoursite.com/

Redirecting 1 file with 301

redirect 301 /old/old.htm http://www.you.com/new.htm

2 Responses to “MOD_REWRITE tips and tricks”


  1. 1 Andres Jul 2nd, 2007 at 7:13 pm

    Special Thanks to www.askapache.com

  2. 2 Daniel Aug 14th, 2007 at 12:05 pm

    I couldn’t understand some parts of this article EWRITE tips and tricks at dpiNYC Literature, but I guess I just need to check some more resources regarding this, because it sounds interesting.

Leave a Reply