nginx 404 500 页面配置

折腾 hexo 博客时候,404 页面必不可少。文章介绍 nginx 如何配置 404 页面。

配置

  1. 页面文件

添加以下配置之前,必须保证你的服务器有文件 /www/public/error/500.html/www/public/error/404.html

  1. 修改 nginx.conf
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
server {
#...

# 404 500 配置
proxy_intercept_errors on;
fastcgi_intercept_errors on;

error_page 404 /404.html;
error_page 500 503 502 /500.html;
location = /500.html {
root /www/public/error/;
}
location = /404.html {
root /www/public/error/;
}

#...
}
  1. 重启 nginx
1
nginx -s reload
  1. 访问任意不存在的地址即可看到效果

proxy_intercept_errors 与 fastcgi_intercept_errors 字段

这两个字段可以配置在 http 模块,也可以配置在 server 模块,还可以配置在 location 模块。

proxy_intercept_errors

语法: proxy_intercept_errors on|off
默认值: proxy_intercept_errors off
使用字段: http, server, location

这个指令指定如果 nginx 配置的 代理服务器 出现 404 错误,是否让 nginx 拦截处理。

如果服务器中没有开启代理服务,则配置 proxy_intercept_errors on; 无用。

则需要再添加 fastcgi_intercept_errors on; 配置, 这样的话,出现页面错误时也会进行跳转。

fastcgi_intercept_errors

语法: fastcgi_intercept_errors on|off
默认值: fastcgi_intercept_errors off
使用字段: http, server, location

这个指令指定是否传递4xx和5xx错误信息到客户端,或者允许nginx使用error_page处理错误信息。

你必须明确的在error_page中指定处理方法使这个参数有效,如果没有适当的处理方法,nginx不会拦截一个错误,这个错误不会显示自己的默认页面,这里允许通过某些方法拦截错误

nginx 自定义404错误页面配置中有无等号的区别

  • error_page 404 /404.html 可显示自定义404页面内容,正常返回404状态码。
  • error_page 404 = /404.html 可显示自定义404页面内容,但返回200状态码。
  • error_page 404 /404.php 如果是动态404错误页面,包含 header 代码(例如301跳转),将无法正常执行。正常返回404代码。
  • error_page 404 = /404.php 如果是动态404错误页面,包含 header 代码(例如301跳转),加等号配置可以正常执行,返回php中定义的状态码。但如果php中定义返回404状态码,404状态码可以正常返回,但无法显示自定义页面内容(出现系统默认404页面),这种情况可以考虑用410代码替代( header(“HTTP/1.1 410 Gone”); 正常返回410状态码,且可正常显示自定义内容)。

参考文章

https://blog.csdn.net/zzhongcy/article/details/86137326

https://blog.csdn.net/qq_28153553/article/details/80969630

https://blog.csdn.net/masteryee/article/details/83689954

本文由 linx(544819896@qq.com) 创作,采用 CC BY 4.0 CN协议 进行许可。 可自由转载、引用,但需署名作者且注明文章出处。本文链接为: https://blog.jijian.link/2020-03-22/nginx-error-page/

如果您觉得文章不错,可以点击文章中的广告支持一下!