自定义 404 页面不显示

Custom 404 page not displaying

我刚开始使用 Nginx,并进行了基本配置,关于配置 PHP FPM,我将索引文件更改为 index.php 而不是 index.html。我还设法处理了 URL 重写,尽管为简单起见在下面的示例中省略了。

但是在默认的配置文件中,有一个专门用于错误页面的部分,看起来好像已经准备好了"plug and play"。我已经取消注释它们,但它们无法正常工作。我已经在 Whosebug 上解决了一些与 404 相关的问题,每个人似乎都建议将其作为正确的语法。

可能指令的顺序不对,但是,这个来自原始示例配置,所以我不知道为什么它不起作用。

我已经从配置文件中删除了所有注释行,剩下的是:

server {
    listen 80 default_server;
    listen [::]:80 default_server ipv6only=on;

    root /var/www/html;
    index index.php;

    server_name localhost;

    location / {
        try_files $uri $uri/ index.php;
    }

    error_page 404 /404.html;

    error_page 500 502 503 504 /50x.html;

    location ~ \.php$ {
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_pass unix:/var/run/php5-fpm.sock;
        fastcgi_index index.php;
        include fastcgi_params;
    }
}

现在,当我转到 http://localhost/this-page-doesnt-exist 时,浏览器显示文字 File not found.,而不是我的 /404.html 文件的内容。

此外,我的 404.html 文件的权限与 index.php 的权限相同,均为 644。所有者也相同。

有什么问题吗?

try_files 正在将您对 none 存在的文件的请求传递给 index.php。这又将请求发送到 php-fpm。默认情况下,Nginx returns 从 php-fpm 到客户端的响应就是您所看到的。

将您的 php-fpm 配置更新为如下所示,并通知 Nginx 处理响应中的错误代码。

location ~ \.php$ {
    fastcgi_split_path_info ^(.+\.php)(/.+)$;
    fastcgi_pass unix:/var/run/php5-fpm.sock;
    fastcgi_index index.php;
    fastcgi_intercept_errors on;
    include fastcgi_params;
}

文档在这里:fastcgi_intercept_errors