Nginx 商用版 1.5.7 (2013 年) 开始支持 sticky 指令。
文档: https://nginx.org/en/docs/http/ngx_http_upstream_module.html#sticky
Syntax: sticky cookie name [expires=time] [domain=domain] [httponly] [samesite=strict|lax|none] [secure] [path=path];
sticky route $variable ...;
sticky learn create=$variable lookup=$variable zone=name:size [timeout=time] [header] [sync];
Default: —
Context: upstream
开源版有 nginx-sticky-module。
- https://code.google.com/archive/p/nginx-sticky-module/ 原始版本
- https://bitbucket.org/nginx-goodies/nginx-sticky-module-ng/ 最后更新是 2016 年
- https://github.com/Refinitiv/nginx-sticky-module-ng Forked from BitBucket
C 语言写的,BSD 协议。
代码看起来并不复杂,如果需要用到的时候,可以进行一个粗略的 Review。
编译
# 下载 nginx 源码 (2016-04-26)
wget http://nginx.org/download/nginx-1.10.0.tar.gz http://nginx.org/download/nginx-1.10.0.tar.gz.asc
gpg --verify nginx-1.10.0.tar.gz.asc
# 下载 nginx-sticky-module (2015-08-06)
wget https://bitbucket.org/nginx-goodies/nginx-sticky-module-ng/get/1.2.6.zip
unzip 1.2.6.zip
cd nginx-goodies-nginx-sticky-module-ng-c78b7dd79d0d/
unzip nginx-1.10.0.zip
cd nginx-1.10.0/
# 其他参数按需添加
./configure --add-module=../nginx-goodies-nginx-sticky-module-ng-c78b7dd79d0d/
make && make install
# Configuration summary
# + using system PCRE library
# + OpenSSL library is not used
# + md5: using system crypto library
# + sha1: using system crypto library
# + using system zlib library
# nginx path prefix: "/usr/local/nginx"
# nginx binary file: "/usr/local/nginx/sbin/nginx"
# nginx modules path: "/usr/local/nginx/modules"
# nginx configuration prefix: "/usr/local/nginx/conf"
# nginx configuration file: "/usr/local/nginx/conf/nginx.conf"
# nginx pid file: "/usr/local/nginx/logs/nginx.pid"
# nginx error log file: "/usr/local/nginx/logs/error.log"
# nginx http access log file: "/usr/local/nginx/logs/access.log"
# nginx http client request body temporary files: "client_body_temp"
# nginx http proxy temporary files: "proxy_temp"
# nginx http fastcgi temporary files: "fastcgi_temp"
# nginx http uwsgi temporary files: "uwsgi_temp"
# nginx http scgi temporary files: "scgi_temp"
用法
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];