NGINX error_page
背景
网络架构中需要遇到apisix,想做个apisix 访问出错的兜底方案
nginx配置
其中http://11.11.11.11:9080
是apisix访问地址
server {
listen 80;
server_name sfimplat;
index index.html index.htm;
root /app/sfimplat_micro/web;
#charset koi8-r;
access_log logs/access.log main;
location /sfimplat {
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass http://11.11.11.11:9080;
}
error_page 500 502 503 504 /50x.html;
location = /40x.html {
root html;
}
location = /50x.html {
root html;
}
}
实操
error_page 可以捕获状态码,因此最开始我是这样配置的
server {
listen 80;
server_name sfimplat;
index index.html index.htm;
root /app/sfimplat_micro/web;
access_log logs/access.log main;
location /sfimplat {
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass http://11.11.11.11:9080;
}
location @fallback {
proxy_pass http://11.11.11.11:18084;
}
#error_page 500 502 503 504 /50x.html;
error_page 503 = @fallback;
location = /40x.html {
root html;
}
location = /50x.html {
root html;
}
}
反复试验后发现流量无法转入 location @fallback
后来发现 error_page
默认仅仅捕获nginx本身的响应状态码,如果想捕获到nginx
的upstream
的状态码,应该配置proxy_intercept_errors on;
server {
listen 80;
server_name sfimplat;
index index.html index.htm;
root /app/sfimplat_micro/web;
access_log logs/access.log main;
location /sfimplat {
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass http://11.11.11.11:9080;
proxy_intercept_errors on;
error_page 503 = @fallback;
}
location @fallback {
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass http://11.11.11.11:18084;
}
error_page 500 502 503 504 /50x.html;
location = /40x.html {
root html;
}
location = /50x.html {
root html;
}
}
参考资料:
http://nginx.org/en/docs/http/ngx_http_core_module.html#error_page
http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_intercept_errors
https://stackoverflow.com/questions/66651410/nginx-fallback-to-alternative-upstream-on-502-and-503