2

My site works both with and without the www subdomain (i.e., both example.com and www.example.com work). However, anything.example.com also works and the same website content is served.

How can I disable all subdomains except www.example.com? I want all other subdomains to return a 404 error or just not show anything.

The config now is as follows:

NameVirtualHost *:80

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

        ...
</VirtualHost>

3 Answers 3

1

Add to VirtualHost config and enabled mod_rewrite:

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

put

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]
1
  • 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. Apr 29, 2014 at 6:34
0

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
</VirtualHost>

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

3
  • Thanks! Can I send 404 from catchall using apache config only?
    – Andrey
    Feb 19, 2011 at 12:20
  • Strictly speaking it's not a 404 as the resource has been found.
    – user9517
    Feb 19, 2011 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, 2011 at 13:27

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .