Reputation: 71
Alright, what I'm wanting to do is create a .htaccess that will redirect any 404 error to another page while capturing the path/file attempted to be accessed.
So, if they are trying to access
www.mydomain.com/xxx
I want it to be redirected to
www.mydomain.com/error.php?e=xxx.
I've never been overly good at writing .htaccess files so any help someone could provide would be WONDERFUL.
I would need this to work sitewide. Thank you in advance!
Upvotes: 1
Views: 457
Reputation: 6159
You don't need a RewriteRule to achieve this.
Just use the ErrorDocument
directive.
It will serve the page you reference but will NOT redirect to it.
If your ErrorDocument
page is a php script, you can then access $_SERVER['REQUEST_URI']
to know what the not found resource was.
So, basically, you just need this in your .htaccess
file:
ErrorDocument 404 /error.php
And in error.php
:
$notFound = $_SERVER['REQUEST_URI'];
Or whatever variable you want to store that URI in.
The good thing is, since the user is not redirected to the page, a simple typo is easy to correct to go to the right page, whereas redirecting would force the user to type the whole URL again (also, he/she wouldn't be able to see what he/she tried to access).
From an analytics point of view, it's still a 404 without any extra code. Redirecting to an error page would force you to add an extra 404 header to it (so robots don't index your error page, among other things).
In error.php
, make sure all your asset paths are absolute, as it might be delivered from http://www.example.com/xxx/yyy
and will look for relative assets from /xxx/
(this path might not exist). So, even tho error.php
is located in your root folder, using src="img/404.png"
will not work as soon as the 404 has a folder in its URI. You have to use src="/img/404.png"
.
Upvotes: 1
Reputation: 785098
You can use this rule in your site root .htaccess:
RewriteEngine On
# If the request is not for a valid directory
RewriteCond %{REQUEST_FILENAME} !-d
# If the request is not for a valid file
RewriteCond %{REQUEST_FILENAME} !-f
# rewrite to error.php with a query parameter
RewriteRule .+ error.php?e=$0 [L,QSA]
Upvotes: 2