Apache: Page Redirect From Old Domain to New Domain Using .htaccess

Lets say you moved your blog site to a different domain. The problem is Google has already indexed all your individual blog article pages on your old domain. You would like all the old links to any of your pages to be redirected to the exact same page of your new domain. When you need to redirect users to a different domain you can use .htaccess to do this. What you can also do with .htaccess is redirect to the exact page you want by rewriting the domain but keeping the remainder of the path including the url query string intact.

Create this .htaccess file in your old domain root. All requests to your old site will be redirected to your new domain to the correct page.

Options +FollowSymLinks
RewriteEngine On
RewriteRule ^(.*) http://www.newdomain.com%{REQUEST_URI} [R=302,NC]

When doing a rewrite must have the ‘Options +FollowSymLinks’ and ‘RewriteEngine On’ set.

The rewriterule will take all requests and point to your new domain and keep whatever directories, file name and query string is in your old links.

R=302 is the HTTP code ‘PERMANENTLY MOVED’

NC – means case insensitive

Site in different sub-directory

Lets say that your old site was under a subdir and not directly in the domain root and your new site is in the root directory. The above method will not work because the old links will be looking for the sub-directory which doesn’t exist on your new site. You will have to do a slight modification to the .htaccess file. As in previous example you place this .htaccess in root of your old site.

Options +FollowSymLinks
RewriteEngine On
RewriteCond %{REQUEST_URI} ^/subdirname/(.*)$
RewriteRule ^(.*) http://www.katcode.com/%1 [R=302,NC]

You write a condition that will detect your old domain sub-directory name and extract everything after it and then affix that portion to the path of your new domain. Replace subdirname with the dir your old site was is in.

The RewriteCond will return everything after the subdirname in the url as the %1 variable. You then place this to the end of your new domain. When anyone clicks a link to your old site they will seamlessly be redirected to the correct page on your new site.

Leave a comment

1 Comments.

  1. Nice tutorial…. thanks !!!

Leave a Reply


[ Ctrl + Enter ]