Configuring Apache to Restrict Access by IP Address
To prevent direct access to a web site via its IP address while allowing access through a designated domain name, modify the Apache configuration file, typical named httpd.conf or included virtual host files. This involves setting up virtual hosts to handle requests differently based on the server name.
Two primary methods exist for implementing this restriction. Both require editing the configuration file and restarting the Apache service to apply changes.
Method 1: Deny All IP Access
Add the following configuration at the end of the file, replacing 192.168.1.191 with the server's public IP address and adjusting paths as needed:
NameVirtualHost 192.168.1.191
<VirtualHost 192.168.1.191:80>
ServerName 192.168.1.191
<Location />
Order Allow,Deny
Deny from all
</Location>
</VirtualHost>
<VirtualHost 192.168.1.191:80>
DocumentRoot "/var/www/html"
ServerName example.com
</VirtualHost>
In this setup, the first virtual host blocks all requests to the IP address, returning a denial response. The second virtual host permits access via the domain name example.com, serving content from the specified document root.
Method 2: Redirect IP Access to a Default Page Alternatively, direct IP-based requests to a separate directory, which can contain a placeholder page, while allowing domain access to the main site:
NameVirtualHost 192.168.1.191
<VirtualHost 192.168.1.191:80>
DocumentRoot "/var/www/default"
ServerName 192.168.1.191
</VirtualHost>
<VirtualHost 192.168.1.191:80>
DocumentRoot "/var/www/html"
ServerName example.com
</VirtualHost>
Here, the first virtual host serves content from /var/www/default for IP access, which could include an informational page. The second virtual host handles domain requests normally.
Implementation Notes
- Ensure the IP address specified matches the server's public IP. For load-balanced environments, use the internal IP address.
- Remove any extraneous spaces or characters whenn copying configurations to avoid syntax errors.
- After modifying the file, restart Apache using a command like
sudo systemctl restart apache2orsudo service httpd restart, depending on the system.
Example Configuration for a Specific Setup
For a server with IP 192.168.1.191 and domain mail.domain.com, using port 99, the configuration might look like this:
NameVirtualHost 192.168.1.191
<VirtualHost 192.168.1.191:99>
ServerName 192.168.1.191
<Location />
Order Allow,Deny
Deny from all
</Location>
ErrorLog "logs/ip_error_log"
CustomLog "logs/ip_access_log" common
</VirtualHost>
<VirtualHost 192.168.1.191:99>
DocumentRoot "/usr/local/app/data/www"
ServerName mail.domain.com
ErrorLog "logs/domain_error_log"
CustomLog "logs/domain_access_log" common
</VirtualHost>
This configuration logs IP and domain accesses separately and enforces the restriction effectively.