My apache server has numerous VirtualHosts and I'd like to have one rule that would redirect the naked domain for all of them to the www domain. Is this possible?


Based on the other answer, I was able to get it to work by creating a catch-all VirtualHost at the bottom of the file that redirect a request to a named www host

<VirtualHost *:80>
  ServerName default
  ServerAlias *
  <IfModule mod_rewrite.c>
    RewriteEngine on
    # WITH 'www.'
    RewriteCond %{HTTP_HOST} !^www.(.*) [nocase]
    RewriteRule ^(.*)$ http://www.%{HTTP_HOST}$1 [redirect=permanent,nocase,last]
| improve this answer | |
  • Only one VirtualHost section matches each request, so not sure how you can have this, and other VirtualHosts... Unless you don't have multiple VirtualHosts. – fukawi2 Dec 18 '12 at 2:00
  • 1
    I think it works like this: the naked domain request matches this catch-all vhost and gets rewritten as a www.* request which matches a named vhost. jamiekrug.com/blog/index.cfm/2009/8/6/… – sguha Dec 18 '12 at 2:05
  • I was also inspired by this answer stackoverflow.com/a/3213665/1218575 – sguha Dec 18 '12 at 2:07
  • I see, clever! I like it :) What happens when fake.com gets redirected to www.fake.com that doesn't have a specific named host, so matches the catch-all vhost again? You'll need to 403 that or something... – fukawi2 Dec 18 '12 at 3:36

Something like this should work:

RewriteCond %{HTTP_HOST} !^www.(.*) [nocase]
RewriteRule ^/(.*)$ http://www.%1/$1 [redirect=permanent,nocase,last]
  1. The RewriteCond matches any HTTP_HOST that does NOT start with www.
  2. The RewriteRule prepends www. to the back-reference to RewriteCond (%1) then appends whatever the actual request was with the back-reference to the RewriteRule match string
| improve this answer | |
  • 2
    Note that this could have the undesired side effect of redirecting non-www subdomains like login.example.com to potentially nonexistent www subdomains like www.login.example.com. – Skyhawk Dec 17 '12 at 23:38
  • @MilesErickson is there any way to fix that? – sguha Dec 17 '12 at 23:46
  • Also these rules just go at the bottom of the httpd.conf file? – sguha Dec 17 '12 at 23:47
  • 1
    Good point @MilesErickson I didn't think of that. If they're all .com domains then you could modify the RewriteCond to have a more specific regex such as RewriteCond %{HTTP_HOST} !^www.(.*\.com)$ [nocase] And yes, that goes in the httpd.conf (or an included config file such as /etc/httpd/cond.d/*.conf on RedHat based systems) – fukawi2 Dec 17 '12 at 23:52
  • Sorry, I'm still not clear on where these rules go. I put them at the bottom of the file and it looks like it's not working. Should they go inside a <VirtualHost> section? – sguha Dec 18 '12 at 0:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.