How to redirect the server to the default error page from the error code specified by the header () function?

I want to know if it is possible to automatically redirect the apache server to the default page from the error code set in the header () function.

let's say I have a page.php page, this page has:

<?php header("HTTP/1.1 404 Not Found"); ?> 

The browser (using the web developer tools in chrome) shows that the response has been sent, but it is not redirected to the default error page, perhaps because the file still exists.

what I want to do is redirect certain files to the default error pages, but keeping the exact URL in the browser is the same action the server does when entering a nonexistent URL

+4
source share
3 answers

If I remember correctly, you can simply configure Apache to use a specific 404 page in httpd.conf and it will support the URL the same, but deliver a 404 error page:

 ErrorDocument 404 /404.php 

and in /404.php, just put something like:

 <html> <head> <title>Object not found</title> </head> <body> <h1>Object not found</h1> <p>The object <?php echo($_SERVER['PHP_SELF']); ?> could not be found on this server.</p> </body> </html> 
+1
source

To get the HTTP response code, you can use the http_response_code () function. Example:

 if( http_response_code() == 404 ) { // Redirect to your valid custom page header("Location: http://www.mypage.com/page_not_found.php" ); } 
0
source

Redirect to a page that does not exist. Then you get the apache created by 404 because you really got to a page that does not exist.

This allows you to β€œdecide” who gets this page and who bounces. Of course, if they have the "nofollow" directive in their web client, it will fail.

I do not know how to get along. You have a php page. And ask apache to solve 404 after checking this page. He has already given up control of PHP. Thus, you probably need to defer the request back to apache, rejecting it to a nonexistent file. You can even laugh and redirect a single file name ... but end it with .html instead of php, and if that doesn't exist, then you have a 404 error for web browsers.

0
source

Source: https://habr.com/ru/post/1443894/


All Articles