Guide to .htacess Redirect Same File Type To Same Domain

I’m adding this guide to my site since it apparently doesn’t exist on the web yet (odd as that seems).  .htaccess files are great and handy but the online info about them is sketchy at best.  Everyone seems to have the same 5 examples on their page, copied verbatim from someone else’s site without any extra explanation.

So here was my quandry…

It’s well known how to redirect single pages (note the first option is the page being moved and is a relative location from the main domain directory while the second option is the absolute location to the new file – even if it is the same domain):

Redirect 301 /oldpage.html http://www.domain.com/newpage.html
Redirect 301 /oldpage2.html http://www.domain.com/newpage2.html
Redirect 301 /oldpage3.html http://www.domain.com/dir/
Redirect 301 /oldpage4.html http://www.domain.com/dir/newpage4.html

Or whole sites:

 Redirect 301 / http://www.newdomain.com/

But if you want to do a certain type of files (like all .html files but not every file on the domain) it gets trickier.  Your fine if you want to change servers:

RedirectMatch (.*)\.gif$ http://www.newdomain.com$1.gif

Or change file types:

RedirectMatch 301 /(.*)\.htm$ http://www.domain.com/oldsite/$1.html

But if you want to simply redirect old site links to a folder/directory on the same site you quickly will discover a problem with endless loops as the somefile.html redirect to /dir/somefile.html will keep getting redirected resulting in a url with /dir/dir/dir/dir/dir/dir/dir/….

[ This will result in a endless loop ]

RedirectMatch 301 /(.*)\.html$ http://www.domain.com/oldsite/$1.html

Since most people online are passing on magic code they really don’t understand, the syntax can take a while to understand. So here is the code you need to make it work:

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_URI} !^/dir(.*)
RewriteRule ^(.*)\.html$ http://domain.com/dir/$1.html [R=301,NC,L]
</IfModule>

The <if> isn’t necessary but good programming. This doesn’t redirect if the directory name is in the url already.  The R=301 is the redirect code. The NC makes capitialization not matter.  And the L makes it quit at that point (if you have other rewrite options). Enjoy and thank the apache gods it didn’t take 3 hours of useless googling to figure this out.