首页 > 解决方案 > NGINX 自定义错误 500 页面未显示

问题描述

我试图捕捉 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/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 收到错误 500,而不是 50x.html 文档?

标签: nginxnginx-config

解决方案


将您的 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;

推荐阅读