Mar 04

mod_rewrite tricks

by in apache, Techie :: Techno ::

Mod_rewrite is an incredibly powerful tool and a lot of us would be very lost without it!
 A couple of quick “tricks” using mod_rewrite – partially to help myself find them again in the future:

 Redirecting domain.tld to www.domain.tld

RewriteEngine On

RewriteBase /
RewriteCond %{HTTP_HOST} !^www.domain.tld$ [NC]

RewriteRule ^(.*)$ http://www.domain.tld/$1 [L,R=301]

 This can be put in a .htaccess in the website’s root.

It will match any HTTP request that is NOT for www.domain.tld and rewrite it to www.domain.tld

Changing File Extensions

If you have changed file extensions on a site, for example moving all files from being “.htm” to “.php” then this line of code will save you a lot of hassle.
Not only will it help with any inbound links, but also for any internal links that you need to edit, but haven’t:

 RewriteRule ^(.*).htm$ $1.php [R=301]

the first file extension in the line is the one you are replacing, while the second is the replacement.

Related Posts:

Tags: ,

3 Responses to “mod_rewrite tricks”

  1. From steviewdr:

    AddHandler application/x-httpd-php .html .htm
    in a .htaccess file would be another idea.

    Posted on March 4, 2007 at 7:34 pm #
  2. From michele:

    You could do that, but why bother? :)

    Posted on March 4, 2007 at 7:35 pm #
  3. From Michele Neylon:

    Having said that .. I’ve had to actually do that on here since I moved over to MT so that I could keep using a particular 3rd party service!

    Posted on September 28, 2007 at 1:41 pm #