記錄 Nginx 0.7.58 套用 upstream_hash 模組實現 URL 雜湊分發的完整編譯安裝與配置流程,適用於需會話親和性的叢集場景。
tar -zxvf pcre-8.02.tar.gz
cd pcre-8.02
./configure && make && make install
tar -zxvf nginx-0.7.58.tar.gz
tar -zxvf Nginx_upstream_hash-0.3.1.tar.gz
cd nginx-0.7.58
patch -p0 < ../nginx_upstream_hash-0.3.1/nginx.patch
groupadd www
useradd -g www www
./configure \
--prefix=/usr/local/webserver/nginx \
--user=www --group=www \
--add-module=../nginx_upstream_hash-0.3.1 \
--with-http_ssl_module \
--with-http_stub_status_module
make && make install
/usr/local/webserver/nginx/sbin/nginx -t
/usr/local/webserver/nginx/sbin/nginx
# /usr/local/webserver/nginx/conf/nginx.conf
user www www;
worker_processes 10;
error_log logs/error.log;
worker_rlimit_nofile 51200;
events {
use epoll;
worker_connections 51200;
}
http {
include mime.types;
default_type application/octet-stream;
keepalive_timeout 120;
tcp_nodelay on;
upstream backend_cluster {
server 192.168.1.10:8080;
server 192.168.1.11:8080;
hash $request_uri; # 核心:依請求 URI 雜湊分發
}
server {
listen 80;
server_name your.domain.com;
location / {
proxy_pass https://backend_cluster;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
location /nginx_status {
stub_status on;
access_log off;
}
}
}
#!/bin/sh
# /usr/local/webserver/nginx/nginx.sh
CWD=$(pwd)
case $1 in
start)
/usr/local/webserver/nginx/sbin/nginx
;;
stop)
kill -2 $(ps -ef | grep "nginx/sbin/nginx" | grep -v grep | awk '{print $2}')
;;
restart)
cd "$CWD"
$0 stop
sleep 1
$0 start
;;
*)
echo "Usage: $0 {start|stop|restart}"
exit 1
esac
exit 0
chmod +x nginx.sh
./nginx.sh start|stop|restart
hash $request_uri 確保同一 URL 落在同一後端,維持 Session 一致性jvmRoute 配合 Session 複製或共享儲存 (Redis/Memcached)ngx_http_upstream_consistent_hash,無需第三方補丁