Take the 2-minute tour ×
Server Fault is a question and answer site for system and network administrators. It's 100% free, no registration required.

I use domain.com and www.domain.com for my site on apache. But anything.domain.com also leads to domain.com. How can I disable all subdomains except www.domain.com to show 404 or just don't show anything?

The config now is as follows:

NameVirtualHost *:80

<VirtualHost *:80>
        ServerName domain.com
        ServerAlias www.domain.com



share|improve this question

3 Answers 3

Add to VirtualHost config and enabled mod_rewrite:

RewriteEngine On
RewriteCond %{HTTP_HOST} !^(www\.|)domain\.com$ [NC]
RewriteRule .* - [F]
share|improve this answer


ServerName www.domain.com

and comment out #ServerAlias...

then when you request domain.com you will get to default apache site apache2ctl -S will show you which one is default...

or if you want to do this via mod_rewrite.

RewriteCond %{HTTP_HOST} !^www\.domain\.com$ 
RewriteRule (.*) - [F]

This will give 403 for any request that's not designated for www.domain.com

Or if you want you can redirect them all to www so they don't use the other subdomain options.

 RewriteCond %{HTTP_HOST} !^www\.domain\.com$  
 RewriteRule (.*) http://www.domain.com/ [R=301,L]
share|improve this answer
You forgot to say the most important thing: the default server for apache is the first file on apache/sites-enabled. Very smart move from Apache! I created a a-catch-all config file there and problem solved. –  JohnPristine Apr 29 '14 at 6:34

You can create a catch all vhost. Make sure it is the last vhost you define as anything not previously matched will be caught by it.

<VirtualHost *:80>
        ServerName      catchall
        ServerAlias *
        DocumentRoot /var/www/catchall

To show nothing have a simple blank index.html file in the DocumentRoot of the vhost.

share|improve this answer
Thanks! Can I send 404 from catchall using apache config only? –  Andrey Feb 19 '11 at 12:20
Strictly speaking it's not a 404 as the resource has been found. –  Iain Feb 19 '11 at 12:50
If you want to send a 404, DON'T create a catchall host and don't let your virtualhost match domains except the ones you want results for. Then apache will send the right errors about resources not being found. Don't try to make apache match something and then pretend it didn't! –  Caleb Feb 19 '11 at 13:27

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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