但如果想更精確的把特定 request 導到特定的 server,可以自己來寫 rule。
例如想用 user id 做 despatch,下面的例子是利用 user id 的開頭第一個字元來做決定
server { listen 80; server_name www.domain.com; location ~* /profile/[a-m] { proxy_pass http://server0.domain.com; } location ~* /profile/[n-z] { proxy_pass http://server1.domain.com; } }
如此一來
http://www.domain.com/brian 就會導向 server0
http://www.domain.com/vicky 就會導向 server1
如果 user id 是流水號,那我們就判斷 id 的個位數字
server { listen 80; server_name www.domain.com; location ~* /profile/[0-9]*[02468]$ { proxy_read_timeout 10s; proxy_pass http://server0.domain.com; } location ~* /profile/[0-9]*[13579]$ { proxy_pass http://server1.domain.com; } }
http://www.domain.com/2000 就會導向 server0
http://www.domain.com/2001 就會導向 server1
如果 request 是 http long polling,可以考慮用301 Moved Permanently 的方式讓 client 的 connection keep 在 target server,減少 nginx 的 connection 數量
server { listen 80; server_name www.my-domain.com; location ~* /profile/[a-m] { rewrite ^(.*) http://server0.domain.com$1 permanent; } location ~* /profile/[n-z] { rewrite ^(.*) http://server1.domain.com$1 permanent; } }
有關 location rule 可以參考:高飞鸟 – Highbird » Blog Archive » Nginx的location匹配规则