Restrict direct IP access to website

Solution 1:

And voila, the fix:

<VirtualHost mysite.com:80>
    ServerName mysite.com
    ServerAlias www.mysite.com
    DocumentRoot /home/rotate/public_html
    ServerAdmin [email protected]
    UseCanonicalName Off
</VirtualHost>

NameVirtualHost mysite.com:80
<VirtualHost 192.168.1.1:80>
    ServerName 192.168.1.1
    Redirect 403 /
    ErrorDocument 403 "Sorry, direct IP access not allowed."
    DocumentRoot /usr/local/apache/htdocs
    ServerAdmin [email protected]
    UseCanonicalName Off
    UserDir disabled
</VirtualHost>

<VirtualHost *>
    ServerName server.mysite.com
    DocumentRoot /usr/local/apache/htdocs
    ServerAdmin [email protected]
    UserDir disabled
</VirtualHost>

NameVirtualHost mysite.com:443
<VirtualHost mysite.com:443>
    ServerName mysite.com
    ServerAlias www.mysite.com
    DocumentRoot /home/rotate/public_html
    ServerAdmin [email protected]
    UseCanonicalName Off
</VirtualHost>

The solution was to simply replace the IP with the domain name for all virtualhost settings, except for the one which needs to redirect/restrict direct IP access.

Solution 2:

The answer could be much much simpler.

Just copy this into bottom of httpd.conf (usually located at /etc/httpd/conf)

<VirtualHost *:80>
ServerName localhost
Redirect 403 /
UseCanonicalName Off
UserDir disabled
</VirtualHost>

<VirtualHost *:80>
ServerName www.example.com
DocumentRoot /var/www/html
</VirtualHost>

Then only when visitors access by www.example.com, he can gain access to the server.


Solution 3:

You can't disable direct IP access to your server over HTTPS because the hostname for your virtualhost is encrypted inside the SSL certificate.

Clients must connect to your IP address, download the certificate, read the contents, and then they can verify that the hostname is correct.

The only other way is by enforcing SNI, but you'll cause problems for users that are browsing with older versions of Internet Explorer.