没有重定向的 NGINX 自定义 404 页面

sct*_*lsn 8 nginx

默认情况下,当 NGINX 返回 404 时,它会呈现一些默认的 HTML。例如,类似于:

<html>
<head><title>404 Not Found</title></head>
<body bgcolor="white">
<center><h1>404 Not Found</h1></center>
<hr><center>nginx/1.10.0 (Ubuntu)</center>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

我想自定义此 HTML 但保持 URL 不变。我试过为 404s 设置错误页面:

error_page 404 /404.html
Run Code Online (Sandbox Code Playgroud)

但这首先将浏览器重定向到/404.html.

有没有办法在不重定向的情况下自定义 404 HTML?

rht*_*sjz 4

也许你可以使用nginx 的error_pageand指令来执行以下操作proxy_intercept_errors

详细配置

server {
    ## other config
    ## here the proxy_intercept_errors directive is the key
    proxy_intercept_errors on;
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        ## your 50x.html file parent directory
        root   /var/www; 
    }
    error_page   404  /404.html;
    location = /404.html {
        ## your 404.html file parent directory
        root   /var/www; 
    }
}
Run Code Online (Sandbox Code Playgroud)

nginx 官方网站上的文档:

proxy_intercept_errorserror_page