Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect all Apache 2.2 403 Forbidden to 404 Not Found

I need to redirect all requests on an Apache 2.2 server for any directory that gives a 403 to a 404 not found.

Ex:

  • /xyz or /xyz/ throws a 403 -> redirect to 404
  • /xyz/sometext.txt returns normally.

Looking around, I came across this post:

Problem redirecting 403 Forbidden to 404 Not Found

RedirectMatch 404 ^/include(/?|/.*)$

/include 404 (instead of 403)
/include/ 404
/include/config.inc 404 (instead of 403)

However, the last case for that also returns a 404. Also, it only affects /include/ directory, I was looking more for any forbidden directory. So far I have:

RedirectMatch 404 ^[\/[\w+]]+\/$

Anyone have an idea of how to accomplish this? Thanks,

like image 602
Tui Popenoe Avatar asked Dec 16 '22 00:12

Tui Popenoe


1 Answers

To return 404 not found for any request that is causing 403 today you can do:

ErrorDocument 403 /404.php

And then in /404.php you can add this line to return 404 status to clients:

<?php
# your custom 404 content goes here

# now make it return 404 status to browser
http_response_code(404);
?>

To return 404 for all the requests to directories you can do:

RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ - [L,R=404]
like image 137
anubhava Avatar answered Dec 17 '22 14:12

anubhava