I got a site server.com which I want to be returned when it is directly adressed using server.com or www.server.com but issue a 404 if the webserver gets accessed using its ip or another hostname.

I got something like the following:

<VirtualHost> #This should be used if Host is server.com or www.server.com
ServerName server.com
ServerAlias server.com www.server.com
DocumentRoot /var/www/

<VirtualHost> #This should be used alternatively
RewriteEngine On
RewriteRule (.*) - [R=404]

How can I now set that the second entry should be used if hostname is not server.com or www.server.com?


To answer your question, you can load the alternative virtualhost (second one in your file) first and it should work. (invert the order in the conf file). If the specific hostname (server.com or www.server.com) is not found then Apache will use the first loaded virtualhost that matches.

But if you use only the virtualhost you want (first one in your file - server.com / www.server.com) and nothing else, doesn't Apache do what you want? It will issue a 404 if the hostname is different than the one in ServerName and ServerAlias (IP or other hostnames will be redirected to 404).

(Obs: you don't need to repeat server.com in ServerAlias as it is already in ServerName)

  • No, it will just serve the VirtualHost with ServerName server.com even though it is different from that... – Zulakis Sep 22 '12 at 14:09
  • Putting it first works though, thanks. – Zulakis Sep 22 '12 at 14:11
  • ok - good you have it working now – laurent Sep 22 '12 at 14:19

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.