Redirecting to HTTP error documents without changing the request URL

帅比萌擦擦* 提交于 2020-01-03 17:31:55

问题


I'm trying to show an HTTP error document from a PHP page, but I would like the original URL to remain in the address bar to prevent search engine crawlers getting confused and to allow for reloading of the page in case it's a temporary issue.

I made a redirect function in PHP which goes a bit like this:

public static function Redirect($url, $code = '303 See Other') {
    header('HTTP/1.1 ' . $code);
    header('Location: ' . $url);
    exit(0);
}

If I want to display an error document, such as 403 Forbidden, I would do the following: Redirection::Redirect('/errordocs/403.php', '403 Forbidden'); and it would work fine.

As I said though, the users URL will change to /errordocs/403.php which I want to avoid.

What I did try to do was remove the header('Location: ' . $url); line if the HTTP code was 4xx or 5xx. I was hoping this would then trigger Apache to display the correct document as I have my .htaccess set up to point to the relevant error pages (which works fine as it is).

What I actually got from doing this was the standard Google Chrome messages for when stuff breaks rather than my pretty custom error documents.

In a quick consensus, what's the best way of doing this now? Making it echo the page instead of redirecting?


回答1:


You can just display the contents of the error html in case of an 4xx status code. Otherwise redirect:

public static function Redirect($url, $code = '303 See Other') {
    header('HTTP/1.1 ' . $code);
    if(strpos($code, '4') === FALSE) {
        header('Location: ' . $url);
    } else {
        include(get_error_page_file_name($code));
    }
    exit(0);

}

The above example will send proper HTTP status code, will display the contents of the error page and keeps your url in the address the same.




回答2:


I just did the same thing but since it's a 404 - not found - in my opinion - it's gone...

So I set my .htaccess file like this:

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule (.*) - [G]
ErrorDocument 410 /error404.php

Now anytime someone hits the 404, it shows the pretty 404 page but stays on the present url

NOTE: here's a working example of the .htacesss file: http://www.smdailyjournal.com/stackoverflow

And when you go to Check the Header Codes you will see it returns a true 410 - Gone message :)



来源:https://stackoverflow.com/questions/14006934/redirecting-to-http-error-documents-without-changing-the-request-url

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!