背景
網路架構中需要遇到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