Redirect instead of 404 Error page - Status Code not working (Nginx)

放肆的年华 提交于 2019-12-12 20:25:42

问题


I'm currently moving to an nginx server. I tried putting this in my 404 ErrorDocument named 404.php:

<?php
    header("Location: http://www.google.com/");
?>

If I now try to access http://mydomain.com/404.php, this works as expected: It redirects me to Google. But once I try to access http://mydomain.com/iDoNotExist, the 404 ErrorDocument is shown without redirecting me to Google.

This behavior seems weird to me. Is there any way I can fix this?

Edit:

Here's what curling the page gives me:

curl -I mydomain.com/404.php

HTTP/1.1 302 Moved Temporarily
Server: nginx/1.2.1
Date: Sun, 05 Jan 2014 11:31:15 GMT
Content-Type: text/html
Connection: keep-alive
X-Powered-By: PHP/5.4.4-14+deb7u7
Location: http://google.com/

curl -I mydomain.com/iDoNotExist

HTTP/1.1 404 Not Found
Server: nginx/1.2.1
Date: Sun, 05 Jan 2014 11:33:49 GMT
Content-Type: text/html
Connection: keep-alive
X-Powered-By: PHP/5.4.4-14+deb7u7
Location: http://google.com/

Edit 2:

As asked by hakre, I'm coming from an Apache setup, and yes, I'm using Chromium. As for Apache, this used to work for all the Gecko and Webkit browsers and even console-based browsers such as Lynx. It would probably have worked for Internet Explorer as well, but I've never tried that (no Windows around here, phew).


回答1:


The behavior of your browser is correct. The Location: response header has no meaning for status code 404 (compare 14.30 Location and 10.4 Client Error 4xx).

Therefore the response's hypertext body is displayed in the browser - as specified by the HTTP specs for code 404 (see 10.4.5 404 Not Found).


To allow changing the HTTP response code from 404 to a different one (e.g. 302 for the temporary redirect), you have to configure Nginx error_page directive accordingly:

error_page   404 = /404.php;

Without the equal sign (=), it is not possible to change the status code with your PHP script:

header("Location: http://google.com"); # PHP sets 302 status code

SAPI: php5-fpm



来源:https://stackoverflow.com/questions/20932750/redirect-instead-of-404-error-page-status-code-not-working-nginx

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