Suppose I have a simple directory structure like the following:

  - index.html
  - 404.html

And a simple configuration like this:

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

How can I prevent direct access to 404.html, i.e. when someone tries to access http://example.com/404.html directly, return a status code of 404 NOT FOUND, plus the content of 404.html?

Right now, if I access the URL directly, it will return 200 OK. If I tries to modify the status code via mod_rewrite:

<Location /404.html>
    RewriteEngine On
    RewriteRule .* - [R=404,L]

then an actual 404, e.g. http://example.com/not-exist.html, will return the following error:

The requested URL /not-exist.html was not found on this server.

Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request.

So, how can I hide the 404.html from visitors, but still use it as the custom 404 error page?


After looking at a similar situation, I found the solution to this problem - there's a variable named REDIRECT_STATUS[ref] that will be set by apache when apache looks up the ErrorDocument internally.

So using the variable, I can add a new rewrite condition to allow apache to exclude actual 404 from being rewritten:

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

and it solved my issue.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.