How to Return Forbidden if Apache HTTPS Is Accessed Directly Using IP

Here’s an example of how you can configure your Apache web server to return a “403 Forbidden” error if the HTTPS is accessed directly using the IP address. This configuration assumes that you have the mod_ssl module installed and enabled in your Apache server.

Step 1: Create or Edit the Apache Configuration File

Open the Apache configuration file in a text editor. The location of the configuration file may vary depending on your operating system and Apache installation. Common locations include:

  • Ubuntu/Debian: /etc/apache2/sites-available/default-ssl.conf
  • CentOS/RHEL: /etc/httpd/conf.d/ssl.conf

Step 2: Add the Configuration Block

Inside the <VirtualHost *:443> block, add the following configuration directives:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
<IfModule mod_ssl.c>
    # Make sure use default as server name
    ServerName default
    DocumentRoot /var/www/html
    <Directory /var/www/html>
        Options -Indexes
        Require all denied
    </Directory>
    SSLEngine on
    SSLCertificateFile /etc/ssl/certs/ssl-cert-snakeoil.pem
    SSLCertificateKeyFile /etc/ssl/private/ssl-cert-snakeoil.key
    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

The Require all denied directive ensures that all requests to the document root (/var/www/html in this example) are denied. This means that if someone tries to access the website directly using the IP address, they will receive a “403 Forbidden” error.

Make sure to replace /var/www/html with the actual path to your web root directory.

Step 3: Save and Exit

Save the changes to the configuration file and exit the text editor.

Step 4: Restart Apache

Restart the Apache web server to apply the new configuration. The command may vary depending on your operating system. Here are some common commands:

  • Ubuntu/Debian: sudo service apache2 restart
  • CentOS/RHEL: sudo systemctl restart httpd

Conclusion

By following the steps above, you can configure your Apache web server to return a “403 Forbidden” error when someone tries to access your website directly using the IP address over HTTPS. This adds an extra layer of security and ensures that your website is accessed through the intended domain name or hostname.

0%