Nginx实现404页面的几种方法(三种)
一个网站项目,肯定是避免不了404页面的,通常使用Nginx作为Web服务器时,有以下集中配置方式,一起来看看。
第一种:Nginx自己的错误页面
Nginx访问一个静态的html页面,当这个页面没有的时候,Nginx抛出404,那么如何返回给客户端404呢?
看下面的配置,这种情况下不需要修改任何参数,就能实现这个功能。
server{
listen80;
server_namewww.test.com;
root/var/www/test;
indexindex.htmlindex.htm;
location/{
}
#定义错误页面码,如果出现相应的错误页面码,转发到那里。
error_page404403500502503504/404.html;
#承接上面的location。
location=/404.html{
#放错误页面的目录路径。
root/usr/share/nginx/html;
}
}
第二种:反向代理的错误页面
如果后台Tomcat处理报错抛出404,想把这个状态叫Nginx反馈给客户端或者重定向到某个连接,配置如下:
upstreamwww{
server192.168.1.201:7777weight=20max_fails=2fail_timeout=30s;
ip_hash;
}
server{
listen80;
server_namewww.test.com;
root/var/www/test;
indexindex.htmlindex.htm;
location/{
if($request_uri~*‘^/$'){
rewrite.*http://www.test.com/index.htmlredirect;
}
#关键参数:这个变量开启后,我们才能自定义错误页面,当后端返回404,nginx拦截错误定义错误页面
proxy_intercept_errorson;
proxy_passhttp://www;
proxy_set_headerHOST$host;
proxy_set_headerX-Real-IP$remote_addr;
proxy_set_headerX-Forwarded-FOR$proxy_add_x_forwarded_for;
}
error_page404/404.html;
location=/404.html{
root/usr/share/nginx/html;
}
}
第三种:Nginx解析php代码的错误页面
如果后端是php解析的,需要加一个变量
在http段中加一个变量fastcgi_intercept_errorson就可以了。
指定一个错误页面:
error_page404/404.html;
location=/404.html{
root/usr/share/nginx/html;
}
指定一个url地址:
error_page404 /404.html;
error_page404=http://www.test.com/error.html;
总结
以上所述是小编给大家介绍的Nginx实现404页面的几种方法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对毛票票网站的支持!