I have searched a lot but can't find an answer

When you setup Dynamic Virtual Hosts in Apache, you do something like this:

  RewriteEngine On

  # a ServerName derived from a Host: header may be any case at all
  RewriteMap lowercase int:tolower

  ## deal with normal documents first:
  # allow Alias /icons/ to work - repeat for other aliases
  RewriteCond %{REQUEST_URI} !^/icons/
  # allow CGIs to work
  RewriteCond %{REQUEST_URI} !^/cgi-bin/
  # do the magic
  RewriteRule ^/(.*)$ /var/www/domains/${lowercase:%{SERVER_NAME}}/html/$1

  ## and now deal with CGIs - we have to force a MIME type
  RewriteCond %{REQUEST_URI} ^/cgi-bin/
  RewriteRule ^/(.*)$ /var/www/domains/${lowercase:%{SERVER_NAME}}/cgi-bin/$1 [T=application/x-httpd-cgi]

Problem is, you need to create 2 folders: example.com and www.example.com (or create one and a symbolic link to it)

What would be a rewrite rule that could avoid having to create those 2 folders? (or the symlink)

The question applies to NGINX as well

Like this question: Apache vhost with and without 'www'? I don't want to use *.example.com


Add another rewrite rule, that should be before the other one in the config file:

RewriteCond %{SERVER_NAME}  ^www\.(.*)
RewriteRule ^/(.*)$ /www/hosts/${lowercase:%1}/docs/$1

What you're doing here is matching the domain name against a regexp. If the domain name starts with "www.", everything after "www." will be stored in the variable %1. In the next line, you're re-using that variable instead of the entire ServerName.

  • Do I replace my rule completely with yours or should they work together? – MauricioOtta May 8 '13 at 23:48
  • After doing some more testing, I figured that it is not working. If I try domain2.com then Apache serves the default domain: domain1.com It correctly works for www.domain2.com though. But it doesn't work when there's no WWW – MauricioOtta May 9 '13 at 2:30
  • Turn on RewriteLog and see what it says when you acess the URL for which the rewrite isn't working. – Jenny D May 9 '13 at 5:47

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.