NGINX自定义错误500页面未显示

时间:2020-02-17 14:53:20

标签: nginx nginx-config

我正在尝试捕获/位置不存在或为空时NGINX显示的错误500。

server {
    listen       80;
    server_name  localhost;
    root   /usr/share/nginx/html/dist/app;
    index  index.html index.htm;

    error_page 500 502 503 504 /50x.html;
    location = /50x.html {
      ssi on;
      root /usr/share/nginx/html/;
      internal;
    }

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

当我保存并测试它时,NGINX告诉我该配置有效。 但是,当我清除dist文件夹时,出现默认的NGINX错误500。

ls -l of /usr/share/nginx/html/

-rwxrwxrwx   1 root root     43 Feb 17 15:26 50x.html
drwxrwxrwx   2 root root   4096 Feb 17 15:32 dist

如何仍然从NGINX而不是50x.html文档中得到错误500?

2 个答案:

答案 0 :(得分:1)

假设/index.html是经过解释的内容(例如PHP-FPM),则NGINX将默认显示来自FastCGI服务器的错误。

要通过NGINX传递错误,您需要使用fastcgi_intercept_errors

fastcgi_intercept_errors off;

类似地,如果您将请求代理到其他地方的/index.html(FastCGI服务器除外),则可以使用proxy_intercept_errors

proxy_intercept_errors off;

答案 1 :(得分:1)

将您的nginx配置更改为

server {
    listen       80 default_server;
    server_name  localhost;
    root   /usr/share/nginx/html/dist/app;
    index  index.html index.htm;

    error_page 500 502 503 504 /50x.html;
    location = /50x.html {
      ssi on;
      root /usr/share/nginx/html/;
      index 50x.html
      internal;
    }

    location / {
      try_files $uri $uri/ /index.html =500;
    }
}

,您将可以看到自定义错误

➜  ~   curl http://127.0.0.1:32769/
<!DOCTYPE html>
<html>
<head>
<title>Error</title>
<style>
    body {
        width: 35em;
        margin: 0 auto;
        font-family: Tahoma, Verdana, Arial, sans-serif;
    }
</style>
</head>
<body>
<h1>This is My custome error.</h1>
</body>
</html>

基本上,您需要将索引添加到错误位置

 index 50x.html

,如果文件不存在则抛出错误

try_files $uri $uri/ /index.html =500;