upstream { sticky; server 127.0.0.1:9000; server 127.0.0.1:9001; server 127.0.0.1:9002; }
# 参数,解析
sticky [name=route] [domain=.foo.bar] [path=/] [expires=1h] [hash=index|md5|sha1] [no_fallback] [secure] [httponly];
[name=route] 设置用来记录会话的cookie名称 [domain=.foo.bar] 设置cookie作用的域名 [path=/] 设置cookie作用的URL路径,默认根目录 [expires=1h] 设置cookie的生存期,默认不设置,浏览器关闭即失效,需要是大于1秒的值 [hash=index|md5|sha1] 设置cookie中服务器的标识是用明文还是使用md5值,默认使用md5 [no_fallback] 设置该项,当sticky的后端机器挂了以后,nginx返回502 (Bad Gateway or Proxy Error) ,而不转发到其他服务器,不建议设置 [secure] 设置启用安全的cookie,需要HTTPS支持 [httponly] 允许cookie不通过JS泄漏,没用过
官方说明:
name: the name of the cookies used to track the persistant upstream srv; default: route domain: the domain in which the cookie will be valid default: nothing. Let the browser handle this. path: the path in which the cookie will be valid default: / expires: the validity duration of the cookie default: nothing. It's a session cookie. restriction: must be a duration greater than one second hash: the hash mechanism to encode upstream server. It cant' be used with hmac. default: md5 md5|sha1: well known hash index: it's not hashed, an in-memory index is used instead, it's quicker and the overhead is shorter Warning: the matching against upstream servers list is inconsistent. So, at reload, if upstreams servers has changed, index values are not guaranted to correspond to the same server as before! USE IT WITH CAUTION and only if you need to! hmac: the HMAC hash mechanism to encode upstream server It's like the hash mechanism but it uses hmac_key to secure the hashing. It can't be used with hash. md5|sha1: well known hash default: none. see hash. hmac_key: the key to use with hmac. It's mandatory when hmac is set default: nothing. no_fallback: when this flag is set, nginx will return a 502 (Bad Gateway or Proxy Error) if a request comes with a cookie and the corresponding backend is unavailable. secure enable secure cookies; transferred only via https httponly enable cookies not to be leaked via js
4.其他的参数:语法:
以下内容摘录于:
session_sticky [cookie=name] [domain=your_domain] [path=your_path] [maxage=time][mode=insert|rewrite|prefix]
[option=indirect] [maxidle=time] [maxlife=time] [fallback=on|off] [hash=plain|md5]
mode设置cookie的模式: insert: 在回复中本模块通过Set-Cookie头直接插入相应名称的cookie。 prefix: 不会生成新的cookie,但会在响应的cookie值前面加上特定的前缀,当浏览器带着这个有特定标识的cookie再次请求时,模块在传给后端服务前先删除加入的前缀,后端服务拿到的还是原来的cookie值,这些动作对后端透明。如:”Cookie: NAME=SRV~VALUE”。 rewrite: 使用服务端标识覆盖后端设置的用于session sticky的cookie。如果后端服务在响应头中没有设置该cookie,则认为该请求不需要进行session sticky,使用这种模式,后端服务可以控制哪些请求需要sesstion sticky,哪些请求不需要。 option设置用于session sticky的cookie的选项,可设置成indirect或direct。indirect不会将session sticky的cookie传送给后端服务,该cookie对后端应用完全透明。direct则与indirect相反。 maxidle设置session cookie的最长空闲的超时时间 maxlife设置session cookie的最长生存期 maxage是cookie的生存期。不设置时,浏览器或App关闭后就失效。下次启动时,又会随机分配后端服务器。所以如果希望该客户端的请求长期落在同一台后端服务器上,可以设置maxage。 hash不论是明文还是hash值,都有固定的数目。因为hash是server的标识,所以有多少个server,就有等同数量的hash值。