HOWTO: Redirect a site to a single hostname with Apache

There are a number of reasons for making sure that your website is served from a single hostname, that is the address users see in their browser’s location bar.  This post will show you how to do that once with two rewrite rules and never worry againg. A single hostname helps with SEO by not penalizing you for having you content crawled at multiple urls ( vs for example).  Also, SSL certificates are issued to a single domain, if your certificate is for and a user goes to, the user would see a warning about the certicate not matching.  You could also be using hostnames for marketing short urls –, for example.  In all these cases you want visitors to end up at a single domain,  If you’re using Apache to serve your website, you can do this using two simple mod_rewrite directives.  You’ll have to adjust them if you put them in your VirtualHost block or in an .htaccess file.

RewriteCond %{HTTP_HOST} !^
RewriteCond /?(.*)$1 [R=permanent,L]

Why is this technique preferable? Most snippets you’ll see online will show you how to redirect one host name to another. By using the exclamation point to speciy a non-matching pattern, we can redirect any host name pointed at this virtual host to our desired host name with just these two lines. Make sure to include the R=permanent flag as well, so that search engines only index pages using the desired host name.