Linux 301 Redirect Code

I constantly find myself needing .htaccess code for a 301 redirect of some kind. I frequently Google to find what I need. Eventually I bookmarked a couple sites for easy access. However, I finally decided to make the information more readily available and saved a txt file in my code library. No idea why it took me so long to come up with this revolutionary idea [/sarcasm]. Anyway, I thought I’d post it here for posterity and to maybe help someone else find it and add it to their files. Feel free to copy/paste away.

REMOVE HTML EXTENSION


Options +FollowSymLinks
Options +Indexes
RewriteEngine on
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteRule ^([^.]+)$ $1.html [NC,L]

REMOVE PHP EXTENSION


Options +FollowSymLinks
Options +Indexes
RewriteEngine on
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteRule ^([^.]+)$ $1.php [NC,L]

REDIRECT WWW TO NON WWW


Options +FollowSymLinks
RewriteEngine on
RewriteCond %{HTTP_HOST} .
RewriteCond %{HTTP_HOST} !^example.com
RewriteRule (.*) http://example.com/$1 [R=301,L]

REDIRECT NON WWW TO WWW


Options +FollowSymLinks
RewriteEngine on
RewriteCond %{HTTP_HOST} ^example.com [NC]
RewriteRule ^(.*)$ http://www.example.com/$1 [L,R=301]

301 REDIRECT EACH PAGE


Redirect 301 /oldpage.html http://example.com/newpage.html

Enjoy!

Leave a Reply

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

Name *