You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Nginx负载均衡策略需求:分区域固定主备服务器转发流量

Proper Nginx Primary/Backup Failover Configuration for Regional Upstreams

Hey there! That massive weight workaround you're using does technically get the job done, but you’re totally right—it’s not the clean or intended way to set up primary/backup failover in Nginx. Luckily, there’s a built-in, standard directive made exactly for this scenario: backup.

How It Works

The backup flag tells Nginx to only send traffic to that server if all non-backup servers are unavailable. This aligns perfectly with your requirement: keep 100% of traffic on the primary server when it’s healthy, and switch to the backup only when the primary fails.

Revised Configuration

Here’s how to rewrite your upstreams using the proper backup parameter, while keeping your existing session persistence with ip_hash:

upstream US_UPSTREAM { 
    ip_hash; 
    # Primary server: handles all traffic when healthy
    server 2.2.2.2 max_fails=10 fail_timeout=3600s; 
    # Backup server: only used if primary is marked down
    server 1.1.1.1 backup; 
} 

upstream EU_UPSTREAM { 
    ip_hash; 
    # Primary server for EU region
    server 1.1.1.1 max_fails=10 fail_timeout=3600s; 
    # Backup server for EU region
    server 2.2.2.2 backup; 
}

Key Details to Keep in Mind

  • ip_hash compatibility: Your ip_hash directive works seamlessly with backup—users will stick to the same server (primary or backup) as long as their IP stays consistent, preserving session persistence.
  • Failover thresholds: Your current max_fails=10 and fail_timeout=3600s mean Nginx will mark the primary as down after 10 failed connection attempts, and keep it marked down for an hour. Adjust these values if you want faster/slower failover (e.g., max_fails=3 fail_timeout=30s for quicker fault detection).
  • Explicit intent: Unlike the massive weight hack, this configuration makes your primary/backup relationship crystal clear—anyone reading the config will immediately understand your traffic routing strategy, making maintenance way easier.

Testing the Failover

To confirm it works as expected:

  1. Stop the primary server for a region.
  2. Send traffic to that upstream—you’ll see it route exclusively to the backup server.
  3. Restart the primary server; after the fail_timeout period elapses, Nginx will automatically shift traffic back to the primary.

内容的提问来源于stack exchange,提问作者ace

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 09:29:11