Canonical redirect with Apache 2

Yesterday, I wrote on how to configure a canonical redirect in IIS 7.  Today, we’re going to look at how to do the same in Apache2.

What is a canonical redirect?  Most sites are configured (or should be, at least) to serve content to requests for both www and non-www versions of the site (www.example.com and example.com).  Basically, when we have 2 or more domain names being served the same content, we want to ensure that precautions are taken to preserve search engine rankings.  If a search engine sees multiple sites with the exact same content, it is likely to rank those sites lower.  Therefore, we want to ensure that the search engine knows that they are both the same site – and we can do this with a canonical redirect.  The most common canonical redirects send requests from www to non-www, or vice versa.  A canonical redirect issues a 301 moved permanently response to the client accessing the site, which tells search engines when they crawl to only index the content at the source of the redirect.

Here’s how to set up this redirect in Apache.

First, we need to ensure that Apache’s rewrite is enabled:

sudo a2enmod rewrite

Then, in the site configuration file, we need to add the following:

ServerName example.com
ServerAlias www.example.com

The two lines above ensure that Apache will respond to requests for both domains.  We then need to add the following to redirect all requests to the www version of the site:

RewriteEngine on
RewriteCond %{HTTP_HOST} !^www\.test\.net [NC]
RewriteRule ^(.*)$ http://www.test.net$1 [L,R=301]

If you want to redirect all requests to the non-www version of the site, it would look like this:

RewriteEngine on
RewriteCond %{HTTP_HOST} !^test\.net [NC]
RewriteRule ^(.*)$ http://www.test.net$1 [L,R=301]

Save the file, and reload your Apache settings:

sudo /etc/init.d/apache2 reload

Your redirects should now be working correctly.

Leave a Reply

  • (will not be published)

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>