需求:当主服务器出现故障,比如500、502、503、504、404等异常时自动启用备用服务器。
下面是server{}内部核心配置:
location /{ #根据返回异常状态码转发到备用服务器 error_page 404 500 502 503 504 = @backup; } #定义备用服务器 location @backup { #配置备用服务器,可以多台,用upstream xxx方式(下面举栗子) proxy_pass http://192.168.10.10:806; }
多台备用服务器(负载均衡模式,参考https://blog.alipay168.cn/index/detail/item/484.html):
#配置分流模式 upstream myServer { server localhost:805 ; server localhost:806 weight=1 max_fails=2 fail_timeout=10; } server { listen 804; server_name abc.test; index index.php index.html index.htm default.php default.htm default.html; root /www/wwwroot/804; #异常时转发到其它服务器 location /{ error_page 404 500 504 503 502 = @toBackupServer; } #转发到定义好的多台服务器(负载均衡配置) location @toBackupServer { proxy_pass http://myServer; } }
一般反向代理(兼容JWT验证):
比如要把/admin/转发到http://abc.com/admin/下面
#PROXY-START/admin/ location ^~ /admin/ { proxy_pass http://abc.com/admin/; proxy_set_header Host abc.com; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header REMOTE-HOST $remote_addr; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection $connection_upgrade; proxy_http_version 1.1; #授权请求头转发,JWT认证需要 proxy_set_header Authorization $http_authorization; # proxy_hide_header Upgrade; add_header X-Cache $upstream_cache_status; #Set Nginx Cache set $static_file6Q68vuT7 0; if ( $uri ~* "\.(gif|png|jpg|css|js|woff|woff2)$" ) { set $static_file6Q68vuT7 1; expires 1m; } if ( $static_file6Q68vuT7 = 0 ) { add_header Cache-Control no-cache; } } #PROXY-END/admin/