A 301 redirect refers to the HTTP status code that is returned when a HTTP request for a specific resourse is redirected. Here we take a look at the difference between 301 and 302 redirects and show a simple way to implement a 301 redirect using the Apache server's virtual hosts directive.

301 vs 302 HTTP status codes

There are two HTTP status codes that can be used to indicate that a request for a given resource has been redirected. The 301 status code means that a page (resource) has permanently moved to a new location. This status code can be used to designate either the http://www.servername.com or the http://servername.com versions of the URLs on your site as the canonical ones and this allows you to avoid the problem of search engines indexing multiple URLs which all point to the same content.

A 302 status code on the other hand means that a page has temporarily moved to a new location and as such the requester of the page (URL) has to continue to check the original URL instead of being able to permanently update it's records and go directly to the new location on subsequent visits.

Apache virtual host definitions

What you can see below are the two virtual host entries that can be used to define firstly, the canonical version of your site and then secondly, to set up the permanent redirect for another version (in this case the www version). The number of available versions and their names will depend upon how the DNS for your site has been configured. The first virtual host setup is fairly self explanatory and in the second the only change is that we are using the RedirectMatch directive.

<VirtualHost *:80>
  ServerName    servername.com
  DocumentRoot  /var/www/sites/servername.com/current
  <Directory /var/www/sites/servername.com/current
    Order allow,deny
    Allow from all

<VirtualHost *:80>
  ServerName  www.servername.com
  RedirectMatch permanent ^/(.*) http://servername.com/$1

To verify that your configuration is working try not only the redirected version of the sites' root URL but also some other URLs that contain one or more sub-levels and then go though each one and check the response (using something like firebug) from the server for the 301 status; which should be 301 Moved Permanently or something very similar.

Useful links

Matt Cutts - Discussing 302 Redirects

Google - 301 Redirects

SEO Book - .htaccess and 301 Redirects

Filed under: web


There are no comments.