This guide explains how to set up 301 redirects using the htaccess file on an Apache server. Setting up 301 redirects can also be achieved through domain registras (domain redirects) and server control panels (cPanel, Plesk, etc).
This guide explains the following points in order (scroll down to view each) :
What is the purpose of a 301 redirect?
The purpose of a 301 redirect is to move a web page’s address from one location to another.
Are 301 redirects search engine friendly?
Yes! It is the recommended method when permanently moving the contents of a web page to another.
How to set up a 301 redirect?
Go to the public root folder of your website (eg. public_html) and either create a .htaccess file or edit it if it already exists. To create the file, simply upload a htaccess.txt file and rename it to “.htaccess” (without the .txt file extension).
Once the .htaccess file is in the public root folder of the website, add one of the following lines to the file depending on what you wish to achieve.
Redirecting a single file to another file on the same domain
Redirect 301 /old.html /new.html
In this example, “old.html” will be redirected to “new.html”. If you have more files to redirect, copy and paste the line again but replace “old.html” and “new.html” with different files you want to redirect.
Removing a file extension
RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^([^\.]+)$ $1.php [NC,L]
This code can be used to remove the .php file extension from your website’s .php pages. Therefore, “domain.com/page.php” will be changed to “domain.com/page” when trying to load the php page. Simply change “php” to the file extension of your choice.
Redirecting a file extension to another file extension
RewriteEngine On RewriteCond %{REQUEST_URI} .php$ RewriteRule ^(.*).html$ /$1.php [R=301,L]
This example shows the extension .html redirecting to the .php extension.
Redirecting a single file to another file on a different domain
Redirect 301 /old.html http://domain.com/new.html
Old.html will now go to new.html.
Redirecting a domain to a new domain
RewriteEngine on RewriteCond %{HTTP_HOST} ^domain.com [NC,OR] RewriteCond %{HTTP_HOST} ^www.domain.com [NC] RewriteRule ^(.*)$ http://new-domain.com/$1 [R=301,L,NC]
Domain.com will now go to New-domain.com.
Redirecting WWW to non-WWW and vice-versa
Non-WWW to WWW :
RewriteEngine on RewriteCond %{HTTP_HOST} ^domain.com [NC] RewriteRule ^(.*)$ http://www.domain.com/$1 [R=301,L]
WWW to non-WWW :
RewriteEngine on RewriteCond %{HTTP_HOST} ^www.domain.com [NC] RewriteRule ^(.*)$ http://domain.com/$1 [R=301,L]
Redirecting WWW sub-domain to non-WWW sub domain
RewriteEngine on RewriteCond %{HTTP_HOST} www.sub.domain.com$ RewriteRule ^(.*)$ http://sub.domain.com/$1 [R=301,L]