Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How redirect wrong querystring to custom errorpage + 404 status

Tags:

php

.htaccess

I would like to redirect users that use a wrong querystring in the URL to a custom error page while ALSO giving a 404 status through the .htaccess directive

ErrorDocument 404 http://www.domain.com/404.php

EDIT: this does not give 404 but 302!!! The "http://www.domain.com" causes a redirect. Just the local path gives a 404. See also http://httpd.apache.org/docs/2.0/mod/core.html#errordocument

Therefore I made a script in the request-receiving index.php that determines if the querystring is not valid and if so, gives this command:

header("HTTP/1.0 404 Not Found");

BUT this does not redirect via the .htaccess directive ErrorDocument but just gives a 404 status to the visitor.

And when using header("Location: 404.php") you get a 302 status, and when using header("Location: 404.php", true, 404) the status is 404 but it does not go to the custom 404.php page.

Now I use

header ("Location: ", true, 404); 
echo "The URL you use doesn't lead to an existing page, etc.";

But this was not the original plan... How would I make users that use a wrong querystring in the URL redirect to the custom error page while also giving a 404 status through the .htaccess directive ErrorDocument, or is this not possible?

like image 447
C.A. Vuyk Avatar asked Dec 06 '25 10:12

C.A. Vuyk


1 Answers

As far as I'm aware the only way to show the 404 page from PHP is to explicitly redirect to it. The reason is Apache (or whatever web server you're using) has already successfully located a resource to which to direct the client (the PHP script being executed). If the PHP script can't resolve the client's request then it has to handle the sending of 404 headers and displaying the page itself.

You could either redirect

header ("HTTP/1.0 404 Not Found");
header ('Location: http://' . $_SERVER["SERVER_NAME"] . '/404.php');

Or you could include the 404 page into the PHP script that wants to trigger a 404.

header ("HTTP/1.0 404 Not Found");
include ('/path/to/404.php');

EDIT: If you use the first technique (redirection) and want to pass the $_GET to the script so it can determine what's wrong with it, you can do this.

header ("HTTP/1.0 404 Not Found");
header ('Location: http://' . $_SERVER["SERVER_NAME"] . '/404.php?' . http_build_query ($_GET));

If you include the 404.php file then the $_GET will be available to it already

like image 65
GordonM Avatar answered Dec 08 '25 00:12

GordonM



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!