How to block direct access to my custom 404 page in Apache?

Viewed 205

I am using Apache2 as web server in Ubuntu and my root is /var/www/html. In there I have an .htaccess file with

RewriteEngine on
ErrorDocument 404 /custom404.html

in it. This works. When I visit mydomain.com/arandomstring I see the custom404.html page. However, what I want to do is block direct access to custom404.html like domain.com/custom404.html should not work. How would I achieve this? I have searched StackOverflow extensively but found no help in this regard.

1 Answers

You can't simply block all access, since the custom error document needs to be accessible in order to be served.

However, you can block direct access by checking against the REDIRECT_STATUS environment variable, which is empty on the initial request and set to the HTTP status code when an error occurs (eg. "404" in the case of a 404 Not Found).

For example, using mod_rewrite in .htaccess:

RewriteEngine On

RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteRule ^custom404\.html$ - [F]

This serves a 403 Forbidden when /custom404.html is requested directly. Or change F to R=404 to serve a 404 Not Found instead (without triggering a rewrite loop).

UPDATE: If used in a server (or virtualhost) context then you need a slash prefix on the RewriteRule pattern. For example: RewriteRule ^/custom404\.html$ - [F]

    <Location /custom404.html>
       RewriteEngine On
       RewriteCond %{ENV:REDIRECT_STATUS} =""
       RewriteRule .* - [R=404]
    </Location>

It would be simpler (and marginally more efficient) to write it like this (code below) instead (the <Location> wrapper is not required):

RewriteEngine On
RewriteCond %{ENV:REDIRECT_STATUS} =""
RewriteRule ^/custom404\.html$ - [R=404]
Related