Search code examples
apache.htaccessvirtualhost

.htaccess or VirtualHost to block website from direct IP access, yet allow from URL only


I have blocked direct access to my site using IP via virtual host. However, i am not able to use 403 error template defined as error.php

Since error.php is located at /var/www/html/error.php, so its blocked automatically and it errors out Additionally, a 403 Forbidden error was encountered while trying to use an ErrorDocument to handle the request.

enter image description here

Below is my 000-default.conf

ErrorDocument 400 /error.php
ErrorDocument 401 /error.php
ErrorDocument 403 /error.php
ErrorDocument 404 /error.php
ErrorDocument 500 /error.php

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

        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

<VirtualHost *:80>
        ServerName 1.1.1.1
        ServerAlias 2001:2001:2001:2001:2001:2001:2001:2001
        DocumentRoot /var/www/html
        <Location />
            Require all denied
        </Location>
</VirtualHost>

So later i tried to achieve same using .htaccess (after removing the block from 000-default.conf ofcourse), I encountered same error. Can't select custom 403 template because path seems to be blocked. Below were .htaccess contents placed at /var/www/html/

RewriteCond %{HTTP_HOST} ^1\.1\.1\.1$
RewriteRule .* - [F,L]
#RewriteCond %{HTTP_HOST} !^2001\:2001\:2001\:2001\:2001\:2001$

Running Apache/2.4.38


Solution

  • Managed to sort it out. Sharing if it could help someone facing similar issue.

    <VirtualHost *:80>
            ServerName 1.1.1.1
            ServerAlias 2001:2001:2001:2001:2001:2001:2001:2001
            DocumentRoot /var/www/html
            <Directory /var/www/html>
                Order deny,allow
                Deny from all
                Options FollowSymLinks
                <Files error.php>
                    Order allow,deny
                    Allow from all
                </Files>
            </Directory>
            ErrorLog ${APACHE_LOG_DIR}/error.log
            CustomLog ${APACHE_LOG_DIR}/access.log combined
    </VirtualHost>