.htaccess redirect 403 error files to 404 error document

4.5k views Asked by At

I have a folder named control which is contained in the root project folder named project, so the path on localhost forms like this for the control folder: http://localhost/project/control

In the control folder I put a .htaccess file that has the content:

RewriteEngine On
deny from all

At the project root folder i.e project folder i have another .htaccess file that contains the main code, including this 404 error redirection code:

RewriteCond %{REQUEST_FILENAME} !-f  
RewriteCond %{REQUEST_FILENAME} !-d  
RewriteRule ^  errordocs/404.php [L]

Now what I want to do is that whenever 403 error is encountered when opening the control folder it should rewrite it to the same errordocs/404.php page.

3

There are 3 answers

11
Halcyon On

You can match a statuscode with an output page with ErrorDocument

ErrorDocument 404 errordocs/404.php
ErrorDocument 403 errordocs/404.php
5
Sourabh Kumar Sharma On

I was able to solve my problem, i am trying to explain it here, so that it might be helpful to others also, it is working fine for me.

in my project/control/.htaccess file i put the code:

RewriteEngine On
RewriteRule ^$   ../errordocs/404.php [L] 

So whenever the user types the url localhost/project/control/ then he will see the custom 404.php file from errordocs folder which is one directory back, as my aim was to prevent direct access to the control folder. I did not use deny from all instead of that used the above procedure so that i can use the custom error pages for the 403 error, that will be independent of the document root path. Now my project folder can be named to any name the user wishes.

Note: This procedure will return 200 instead of actual 403 error. To return 403 and 404 use the below respective code:

403

RewriteEngine On
RewriteRule ^$  ../errordocs/404.php [L]
RewriteRule ^$ - [R=403,NC,L]

404

RewriteEngine On
RewriteRule ^$  ../errordocs/404.php [L]
RewriteRule ^$ - [R=404,NC,L]
0
fammi farendra On

redirect 403 to 404 in htaccess

ErrorDocument 403 /yourfoldererror/404.php

And in your 404.php add php code like this :

<?php http_response_code(404);?><!DOCTYPE html><html ....

With that code, the response will not 403, but 404