Implementing 301 redirects

Last week I explained what you need to do when you change the domain name on a website and the role of the ‘301 redirect’.  This week, I am going to explain how to actually implement a 301 redirect.

The explanation set out below applies to websites that are hosted on servers running the Apache webserver software.  If your site is hosted on a server running other software, check with your hosting company or software supplier for information on how to do this.

You will need to have access to your website’s .htaccess file and .htaccess directives must be enabled in the server’s configuration file.

You will then need to decide whether to use a “redirect” or a “rewrite”.  If the new file is on the same webserver as the old file, you should use a rewrite. If the file is on a different server, you should use a redirect. Why? The simple answer is bandwidth. A redirect sends the new URL back to the web client and the web client must reissue the URL request, which creates more traffic. With a rewrite, the original request is just processed and a new URL is returned along with the new file – the web client does not have to reissue anything.

Redirects

To use a redirect, the Apache module mod_alias needs to be available on the webserver. This module is compiled and loaded into the server by default, and is therefore normally available unless steps have been taken to remove it.

To use it place the following directive in your .htaccess file.

RedirectMatch permanent ^(.*)$ http://www.newdomain.com$1

(Replace ‘newdomain.com’ with your own new domain name.)

Rewrites

To use a rewrite, the Apache module mod_rewrite needs to be available on the webserver. This module is not compiled and loaded into the server by default, so action needs to be taken to install it.

To use it place the following directives in your .htaccess file.

RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^(www\.)?olddomain\.com
RewriteRule (.*) http://www.newdomain.com/$1 [R=301,L]

(Replace ‘olddomain.com’ and ‘newdomain.com’ with your own domain names.)

If you wish to understand what the various directives are actually doing, I suggest that you consult the Apache documentation, in particular the Apache URL Rewriting Guide.

The directives for both redirects and rewrites can be placed in the server configuration file instead of the .htaccess file, and, indeed, it is more efficient to do it that way, but many hosting companies do not provide access to that file.

I hope that this post provides the answer to what seems to be quite a common problem.

Next week I will get back to less “technical” issues.

2 Comments

MarkSpizerMay 2nd, 2010 at 1:11 pm

great post as usual!

Wordpress ThemesMay 5th, 2010 at 6:05 am

Good brief and this fill someone in on helped me alot in my college assignement. Gratefulness you seeking your information.