Question

Is there a way how I can configure the Apache web server to return a 404 (not found) error code instead of 403 (forbidden) for some specific directories which I want to disallow to be accessed?

I found some solutions suggesting the use of mod_rewrite, like e.g.

RewriteEngine On
RewriteRule ^.*$ /404 [L]

As the purpose of sending 404 instead of 403 is to obfuscate the directory structure, this solution is too revealing, because it redirects to some different location which makes it obvious that the directory originally accessed does in fact exist.

Was it helpful?

Solution

RedirectMatch as in e.g.

RedirectMatch 404 ".*\/\..*"

does the trick, it prohibits access to all files or directories starting with a dot, giving a "404 Not Found" error.

From the Apache manual: "The Redirect[Match] directive maps an old URL into a new one by asking the client to refetch the resource at the new location." By default, Redirect sends a 302 return code, but it can also return other status codes as shown above.

OTHER TIPS

You can make something like this:

.htaccess

ErrorDocument 403 /error/404.php

404.php

<?php
$status = $_SERVER['REDIRECT_STATUS'] = 404;
header( $_SERVER['SERVER_PROTOCOL'] . ' ' . $status);
?>

404 Error

After having the same problem, I ended up with the following .htaccess file

Options -Indexes
RewriteCond %{HTTP_HOST} ^(www\.)?mydomain.com [NC]
RewriteRule ^(.*)/$ - [R=404,NC]

The 1st and 3rd line ensure that you can't list the folder content, and if you do it you will receive a 404 error. The RewriteCond directive ensures that this rewrite rule only applies to main domain. Since I have several subdomains, without the rewritecond, accessing www.mydomain.com/subdomain was also returning a 404, which was not what I intended.

To change all 403,400 errors into 404 errors, put this at the end of /etc/apache2/conf.d/localized-error-pages OR into a .htaccess

# Will raise a 404 error, because the file <fake_file_for_apache_404.php> doesn't exist.
# We change 403 or 400 to 404 !
ErrorDocument 400 /fake_file_for_apache_404.php
ErrorDocument 403 /fake_file_for_apache_404.php
# We need to rewrite 404 error, else we will have "fake_file_for_apache_404.php not found"
ErrorDocument 404 "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\"><html><head><title>404 Not Found</title></head><body><h1>Not Found</h1><p>The requested URL <script type=\"text/javascript\">document.write(document.location.pathname);</script> was not found on this server.</p></body></html>"
ErrorDocument 500 "Server in update. Please comme back later."
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top