
error_page是nginx一个重要的指令,作用是定制化服务器错误页面。当nginx发生内部错误时,比如说404、403、500等错误,默认会跳转到nginx自带的错误页面。但是使用error_page指令可以修改默认错误页面,并且可以指定跳转的url或者文件路径。
语法:
error_page code [ code... ] [ = | =answer-code ] uri | @named_location 默认值:
no 使用字段:http, server, location, location 中的if字段
其原理是响应到错误代码后,导向指定的路由,然后再由指定的路由处理,如下当错误代码是404时,相当于访问http://localhost:80/50x.html,正好被内部传送给 location = /50x.html让其来进行处理(需要注意必须有50x.html这个页面)
error_page 404 403 500 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}其原理是响应到错误代码后,302(临时重定向到目标网址),如下当错误代码为404时,导向https://www.csdn.net
error_page 404 403 500 https://www.csdn.net;server{
error_page 404 @jump_to_error;
location @jump_to_error {
default_type text/plain;
return 404 'Not Found Page...';
}
}本来遇到404找不到文件的错误,但是nginx可以把它状态码改为200返回给用户(例子如下)
error_page 404 =200 /50x.html;#注意这里的缩进不是随便的
location = /50x.html {
root /usr/share/nginx/html;
}注意 error_page 配置时加 = 和不加 = 的区别,加了 = 表示响应为指定的 http status code ,默认为 200,不加 = 为原错误的状态码~
# 这样可以访问错误页面时 http status 为 404 ,并且页面内容是 404.html 的内容
error_page 404 /404.html
error_page 404 500 /404.html;
# 这样配置访问错误页面时 http status 为 200 ,但页面内容是 404.html 的内容
error_page 404 500 = /404.html;
# 这样配置访问错误页面时 http status 为 404 ,但页面内容是 404.html 的内容
error_page 404 500 =404 /404.html;
# 也可以把404请求直接301到某个域上
error_page 404 =301 https://xuexb.com/404;这样就可以根据自己需求配置错误页为指定的状态码,因为非 200 的状态码可能会被浏览器拦截。
由于在nginx配置中,设置了limit_req的流量限制,导致许多请求返回503错误代码,在限流的条件下,为提高用户体验,希望返回正常Code 200,且返回操作频繁的信息:
location /test {
...
limit_req zone=zone_ip_rm burst=1 nodelay;
error_page 503 =200 /dealwith_503?callback=$arg_callback;
}
location /dealwith_503{
set $ret_body '{"code": "V00006","msg": "操作太频繁了,请坐下来喝杯茶。"}';
if ( $arg_callback != "" )
{
return 200 'try{$arg_callback($ret_body)}catch(e){}';
}
return 200 $ret_body;
}error_page后面跟的/error/404.html就相当于其访http://localhost:80/error/404.html其被location /error捕获
error_page 404 /error/404.html;
error_page 403 /error/403.html;
location /error {
alias /var/www/html;
}我正在参与2023腾讯技术创作特训营第二期有奖征文,瓜分万元奖池和键盘手表
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。