Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

redirect 403 error using .htaccess

I want to redirect any 403 using .htaccess, but it does not seem to work.

Options +FollowSymlinks

RewriteEngine on
ErrorDocument 403 notfound.html
RewriteRule notfound.html

All help appreciated.

Thanks Jean

like image 743
X10nD Avatar asked Dec 28 '22 23:12

X10nD


2 Answers

The URL part of an ErrorDocument directive should either start with a leading slash, which indicates a path that's relative to your DocumentRoot, or it should be a full URL (if you want to use an external document).

You shouldn't need the RewriteEngine and RewriteRule directives at all here.

So, assuming your notfound.html is at the root level of your site, your directive should look like:

ErrorDocument 403 /notfound.html
like image 181
John Flatness Avatar answered Jan 10 '23 20:01

John Flatness


I found a problem with the earlier example, which was:

ErrorDocument 403 /notfound.html

I have a directory on my site storing images, say at domain.com/images

I wanted that if someone tries accessing the directory's URL that they be redirected to the site's homepage. My problem was, with the above, that the URL in the browser would remain domain.com/images and then the homepage would load, but the homepage would reference stylesheets that it could not access from that URL. (And it makes sense - 403 is supposed to show an error message).

I then tried researching how to redirect a 403 error to another URL and a few sites said you can't do a 302 or 301 - you're missing the point: 403 is an error, not a redirect.

But I found a way. This is the .htaccess file inside the /images directory:

Options -Indexes
ErrorDocument 403 /images/403.php
RewriteEngine on
RewriteRule ^403.php$ /index.php [R=301]

So basically the first line prevents directory listing.

The second line says that for "permission denied" (ie. 403 error, which is what the first line gives), the site should load the file "/images/403.php". But you don't actually need to create any 403.php file in that directory, because...

The third line turns on your redirect engine

And the fourth line says that if the user attempts to load the page 403.php (ie. in this "/images" directory where this .htaccess file is located) then they should be redirected, using a 301 (permanent) redirect, to /index.php - which is the index of the root directory (ie the homepage), and not the index of the /images subdirectory (and indeed there is no index in "/images" anyway).

Hence - how to get a 403 to redirect to another URL using a 301 (permanent) redirect (or, you could try a 302 temporary redirect too).

like image 28
youcantryreachingme Avatar answered Jan 10 '23 22:01

youcantryreachingme