In Apache, how do I disable access to a website when someone only uses the IP address in a web browser?

I'm using apache web server on CentOS and I need to disable the ability for people to access the website by using the server's IP address in a web browser. I want it so that when someone attempts to browse to the IP address they get a forbidden error message.

What configurations would be necessary to do that?


Solution 1:

Just set up the default virtual host. There is a commented example in httpd.conf or do something trivial like:

<VirtualHost *:80>
    ServerName localhost
    DocumentRoot /var/www/html
</VirtualHost>

Solution 2:

You can achieve this with mod_rewrite (either in the .htaccess file, or in the default server context, or in a separate VirtualHost where the ServerName is the host's IP address):

RewriteEngine On
RewriteCond %{HTTP_HOST} 1.2.3.4 # Replace with your own IP address
RewriteRule .* - [F]

This says that if the HTTP_HOST header matches the ip address 1.2.3.4, then any request should be met with a 403 Forbidden. Any request that has another HTTP_HOST header (e.g. one with the actual domain name rather than the IP address) should not be affected.

Solution 3:

You cannot block direct access by IP. You must allow the connection but then decide what to do with it. This could be return a 403, a 404 or redirect them to the desired page. You can do this with mod_rewrite.

 RewriteEngine On
 RewriteCond %{HTTP_HOST} ^123\.123\.123\.123
 RewriteRule ^(.*)$ - [F,L]

This will match the HTTP HOST header passed by the web client. All other requests would pass through.

However, you may want to normalize your URLs for SEO purposes.

With this approach you rewrite anything that does not match the desired result.

RewriteCond %{HTTP_HOST}   !^fully\.qualified\.domain\.name [NC]
RewriteCond %{HTTP_HOST}   !^$
RewriteCond %{SERVER_PORT} !^80$
RewriteRule ^/(.*)         http://fully.qualified.domain.name:%{SERVER_PORT}/$1 [L,R]

Reference: https://httpd.apache.org/docs/2.0/rewrite/rewrite_guide.html#canonicalurl

Reference: http://en.wikipedia.org/wiki/URL_normalization