Disable direct IP access in apache
Solution 1:
I'm expanding my comment into an answer in order to provide the detailed configuration in response to the OP's further inquiry. My recommendation is moving your config into VirtualHost blocks to allow for increased flexibility. Only the essential bits are shown here:
<VirtualHost *:80>
ServerName default
DocumentRoot /home/admin/web/xxx.com/public_html
<Location />
Require all denied
</Location>
</VirtualHost>
<VirtualHost *:80>
ServerName domain.com
DocumentRoot /home/admin/web/xxx.com/public_html
</VirtualHost>
default
can be any name or the server's IP address.
domain.com
is the domain you want your server to respond to.
Explanation: When called with the IP address, apache elaborates the request with the default VirtualHost. The first VirtualHost defined is the default, regardless of its ServerName. Of course, setting the ServerName to the IP address also works, and will leave the default server free to be used otherwise. The location block denies every request to the whole VirtualHost.
Edit: I later saw that the question is tagged apache-2.2
, while my answer uses apache-2.4
syntax. On apache-2.2
the line Require all denied
must be substituted with two lines: Order deny,allow
and Deny from all
. Additionally, a NameVirtualHost *:80
is required before the VirtualHost
definitions.
Update: The question has been updated so I think it's best to provide the configuration for apache-2.2
, including all necessary lines. The same explanation as above applies.
Listen 8080
NameVirtualHost ipaddress:8080
<Directory "/home/admin/web/xxx.com/public_html">
Order allow,deny
Allow from all
</Directory>
<VirtualHost ipaddress:8080>
ServerName ipaddress
DocumentRoot /home/admin/web/xxx.com/public_html
<Location />
Order deny,allow
Deny from all
</Location>
</VirtualHost>
<VirtualHost ipaddress:8080>
ServerName xxx.com
DocumentRoot /home/admin/web/xxx.com/public_html
</VirtualHost>
Comment: I agree that there are other valid solutions; however, this is how I like to organize my config files, with security restraints inside Directory
or Location
blocks so I know where to look for them.
Solution 2:
the IP will always be accessed (after all thats what your domains point to), what you can do is check which Hostname the request was used to make:
For Instance use mod-rewrite:
RewriteEngine On
RewriteCond %{HTTP_HOST} ^192\.168\.0\.1$
RewriteRule .* - [F,L]
you could also chose to redirect all hostnames you don't like
RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\.thedomainiwant\.com$ [NC]
RewriteRule .* http://www.thedomainiwant.com%{REQUEST_URI} [R=301,L]
alternatively use https:// the rewrite ;-)
Solution 3:
Yet another way using mod_setenvif
SetEnvIf HOST ^[0-9].+[0-9]$ HOST_NODNS
Deny from env=HOST_NODNS
Notice we are using HOST instead of HTTP_HOST.