Setting permanent 301 redirect via .htaccess
Redirect individual files
To redirect individual files, like example.com/oldfile.htm to newfile.htm you can use a 301 redirect like this
1 |
Redirect 301 /oldfile.htm /newfile.htm |
To redirect one specific file to another domain such as example.com/oldfile.htm to example.net/newfile.htm, you need to add the full URL with the domain name.
1 |
Redirect 301 /oldfile.htm http://example.net/newfile.htm |
Redirect an old domain to a new domain
If you have a new domain and want to preserve the traffic and SEO of the old domain, you can write a domain wide redirect. This will tell the browser and the spiders “Hey, I moved to a new address, please update my address on your address book”.
1 2 3 4 |
RewriteEngine on RewriteCond %{HTTP_HOST} ^example.com [NC,OR] RewriteCond %{HTTP_HOST} ^www.example.com [NC] RewriteRule ^(.*)$ http://example.net/$1 [L,R=301,NC] |
Force www./naked version of domain to be used
Search engine see example.com and www.example.com as essentially two separate websites. They recommend you pick one version you’d like search engines to display and using a 301 redirect is a possible option.
This will force all links into the www format.
1 2 3 |
RewriteEngine on RewriteCond %{HTTP_HOST} ^example.com [NC] RewriteRule ^(.*)$ http://www.example.com/$1 [L,R=301,NC] |
This will force all links into the naked format.
1 2 3 |
RewriteEngine on RewriteCond %{HTTP_HOST} ^www.example.com [NC] RewriteRule ^(.*)$ http://example.com/$1 [L,R=301,NC] |
Redirect all files with certain extension
On some rare cases, you may want to change the extension name for your files into something else. The example below will change the php extensions into an htm extension.
1 2 3 |
RewriteEngine On RewriteCond %{REQUEST_URI} .php$ RewriteRule ^(.*).php$ /$1.htm [R=301,L] |