Home > Mobile >  Add URL Parameter To Htaccess Redirect ErrorDocument
Add URL Parameter To Htaccess Redirect ErrorDocument

Time:08-09

On my website, when the user navigates to an invalid url I still want to display what he was looking for but when I redirect to my error.php via .htacces the faulty URL is lost.

I'm using this to redirect (.htaccess):

ErrorDocument 404 https://www.mywebsite.com/error.php

What I want insead is to add the faulty URL to the end of the redirect as URL parameter.

For examplewhen the user navigates to this URL https:www.mywebsite.com/this-does-not-exist I want that to reflect in my error.php as well and add the last part as URL paramater. The URL should then look like this:

https://www.mywebsite.com/error.php?url=this-does-not-exist

I already tried doing ErrorDocument 404 https://www.mywebsite.com/error.php?url=$1 and I also tried ErrorDocument 404 https://www.mywebsite.com/error.php [L] both versions did not give me the desired result.

How can I add the faulty url to the ErrorDocument redirect as url parameter in htaccess?

CodePudding user response:

The easiest way is to use the document root and not the host in your .htaccess IE:

ErrorDocument 404 /error.php

Then in your PHP script error.php you can get the current URL simply by using

$url = $_SERVER[HTTP_HOST] . $_SERVER[REQUEST_URI];
echo "The page $url you are trying to reach doesn't exist!";

All the while KEEPING the current URL

https://www.mywebsite.com/this-does-not-exist

displayed in the URL bar.

  • Related