Arvy
Arvy

Reputation: 1212

Apache htaccess redirect all 404 (files and folders)

I want to redirect to a PHP file all "404" errors. I used .htaccess from Wordpress as initial step. Works, but not when the path is a folder, means, had a "/" at end, I get a Forbidden error.

RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /includes/redir.php [L]

If I try:

http://example.com/anything

works as expected, redirects to my redir.php. But if I try:

http://example.com/anything/

returns a Forbidden error.

What I need to do to redirect to redir.php everything that don't exist? I need to change httpd.conf? I need a "ErrorDocument 404 /includes/redir.php" line?

Upvotes: 1

Views: 1235

Answers (1)

MrWhite
MrWhite

Reputation: 45958

I need a "ErrorDocument 404 /includes/redir.php" line?

Yes, it is far more preferable to use an ErrorDocument directive like this than trying to redirect/rewrite manually to an error document.

The defined ErrorDocument will return the correct HTTP status code (without you having to manually do this). And PHP will set additional variables in the $_SERVER superglobal relating to this error.


If you specifically wanted to rewrite to a file on 404 instead then you could do something like:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ /includes/redir.php [L]

but not when the path is a folder, means, had a "/" at end, I get a Forbidden error.

It really shouldn't matter if the URL "looks" like a folder, unless the URL mapped to a physical folder on disk. Only then would you get a 403 Forbidden if there was no directory index document.

Upvotes: 1

Related Questions