Nginx 负载均衡与高级配置实战指南

📅 2026/8/1 7:46:34
Nginx 负载均衡与高级配置实战指南
1. 负载均衡基础配置1.1 配置 upstream 模块编辑 Nginx 配置文件定义后端服务器组vim /usr/local/nginx/conf/nginx.conf http { upstream backend { server 192.168.150.139 weight2; # 权重为2接收更多请求 server 192.168.150.140; # 默认权重为1 server 127.0.0.1 backup; # 备用服务器仅当所有主服务器失效时启用 } # 定义虚拟主机实现反向代理负载均衡 server { listen 80; server_name www.westos.org; location / { proxy_pass http://backend; # 将请求转发到后端服务器组 } } }配置完成后重新加载 Nginxsystemctl reload nginx1.2 权重与备用机说明权重配置weight2表示该服务器接收请求的概率是其他服务器的两倍备用机限制备用机不能设置为正在使用的主机否则测试会出错代理循环避免如果 upstream 中包含127.0.0.1:80或本机 IP同一监听端口Nginx 会将请求重新发给自身形成代理循环。需要修改本机监听端口来避免将别的机器设置为备用机子当后端全挂了之后会启动备用机1.3 域名解析配置在测试主机上添加域名解析# 编辑 hosts 文件vim/etc/hosts# 添加以下内容192.168.150.139 server5 www.westos.orgWindows 系统可在C:\Windows\System32\drivers\etc\hosts文件中添加相同解析。2. 负载均衡调度算法2.1 ip_hash 算法upstream myapp { ip_hash; # 基于客户端 IP 的哈希算法 server 192.168.150.138; server 192.168.150.140; }特点同一客户端 IP 的请求总是转发到同一台后端服务器不支持 backup 参数如果某台服务器 down 掉该服务器的客户端会一直访问失败Ip哈希算法中将server7down掉就会一直访问62.2 sticky 算法upstream backend { sticky cookie srv_id expires1h path/; server 192.168.150.139; server 192.168.150.140; }配置说明sticky cookie srv_id基于 cookie 的会话保持expires1hcookie 有效期为 1 小时path/cookie 作用于整个站点验证方法使用浏览器访问测试页面按 F12 打开开发者工具查看 Application → Cookies 中的srv_id值报错将本来的westos的server移动到localhost的上面配置文件中存在两个或更多 server 块使用了相同的 server_name “www.westos.org” 和端口 80。Nginx 会忽略后面重复的块只使用第一个匹配的块浏览器访问主机就会跳转或者在文件夹C盘C:\Windows\System32\drivers\etc\hosts打开hosts文件在记事本中编辑加入访问的主机的解析然后才能使用浏览器测试3. Nginx 模块化编译3.1 下载 sticky 模块# 克隆 sticky 模块源码gitclone https://github.com/fabianofurtado/nginx_sticky_module_ng3.2 动态编译推荐# 进入 Nginx 源码目录cdnginx-1.28.3/# 配置编译参数./configure--prefix/opt/nginx\--with-http_ssl_module\--with-http_stub_status_module\--with-compat\--add-dynamic-module../nginx_sticky_module_ng# 编译make# 安装模块/opt/nginx/sbin/nginx-sstopcp-fnginx /opt/nginx/sbin/nginxmkdir/opt/nginx/modulescpngx_http_sticky_module.so /opt/nginx/modules//opt/nginx/sbin/nginx -s stop向当前运行的 Nginx 主进程发送 stop 信号优雅地停止服务不再接受新请求处理完当前连接后退出。cp -f nginx /opt/nginx/sbin/nginx将当前目录下的 nginx 可执行文件强制覆盖到 /opt/nginx/sbin/nginx即替换旧版本的二进制文件。3.3 静态编译./configure--prefix/opt/nginx\--with-http_ssl_module\--with-http_stub_status_module\--add-module../nginx_sticky_module_ngmakemakeinstall想更改编译方式cd nginx-1.28.3/ vim auto/cc/gccmake clean ./configure ....... make (make install)3.4 启用动态模块在nginx.conf顶部添加load_module /opt/nginx/modules/ngx_http_sticky_module.so;重新加载nginx服务4. 连接与请求限制4.1 限制并发连接数mkdir /usr/local/nginx/html/download 创建目录 cp vim.jpg /usr/local/nginx/html/download/ 拷贝测试地图片文件到该目录下# 创建共享内存区域 limit_conn_zone $binary_remote_addr zoneaddr:10m; server { location /download/ { limit_conn addr 1; # 每个 IP 最多 1 个并发连接 } }测试命令ab-c1-n10http://192.168.150.139/download/vim.jpg必须单线程下载超出的并发连接会失败查看错误日志tail-f/usr/local/nginx/logs/error.log4.2 限制请求速率# 定义请求限制区域 limit_req_zone $binary_remote_addr zoneone:10m rate1r/s; server { location / { limit_req zoneone burst5; # 允许突发 5 个请求 # limit_req zoneone burst5 nodelay; # 立即处理突发请求 } }nginx -s reload参数说明zoneone:10m创建 10MB 的共享内存区域rate1r/s限制每秒 1 个请求burst5允许超出速率的请求排队等待最多 5 个nodelay立即处理突发请求超出部分返回 503超出的请求数会失败4.3 限制下载速率server { location /download/ { limit_conn addr 1; limit_rate 100k; # 限制下载速度为 100KB/s } }测试ab-c1-n5http://192.168.150.139/download/vim.jpg# 下载时间约需 20 多秒5. 高级功能配置5.1 自动索引location /download/ { autoindex on; # 启用目录列表 ... }默认访问/download/会返回 403 Forbidden启用autoindex on后会显示目录中的文件列表。5.2 浏览器缓存配置location ~ .*\.(gif|jpg|png)$ { expires 365d; # 缓存 365 天 root html; }配置说明正则匹配所有以.gif、.jpg或.png结尾的请求expires 365d告诉浏览器缓存 365 天root html静态文件根目录为 Nginx 安装路径下的 html 目录测试5.3 日志轮询脚本创建日志轮询脚本/opt/nginx_log.sh#!/bin/bashcd/usr/local/nginx/logsmvaccess.log access_$(date%F-d-1day).logkill-USR1$(cat/usr/local/nginx/logs/nginx.pid)vim /opt/nginx_log.sh切换到 Nginx 日志目录。把当前的 access.log 重命名为 access_YYYY-MM-DD.log其中日期是前一天-d -1day。kill -USR1 \cat /usr/local/nginx/logs/nginx.pid向 Nginx 主进程发送 USR1 信号该信号让 Nginx 重新打开日志文件。此时 Nginx 会新建一个 access.log继续写入新日志而旧日志已被改名保留设置执行权限并添加到定时任务chmodx /opt/nginx_log.shcrontab-e# 添加以下内容每天凌晨执行00 00 * * * /opt/nginx_log.sh执行/opt/nginx_log.shcd/usr/local/nginx/logs/ ll5.4 Nginx 日志可视化GoAccess# 下载并安装 GoAccesswgethttps://tar.goaccess.io/goaccess-1.8.tar.gztar-xzfgoaccess-1.8.tar.gzcdgoaccess-1.8/# 安装依赖yuminstall-yncurses-devel GeoIP-devel libmaxminddb-devel# 编译安装./configure --enable-utf8 --enable-geoipmmdbmakemakeinstall# 启动实时监控goaccess /usr/local/nginx/logs/access.log\-o/usr/local/nginx/html/report.html\--log-formatCOMBINED\--real-time-html# 生成测试流量ab-c100-n400http://192.168.150.139/report.html6. 安全与监控配置6.1 站点限制location /status { stub_status on; # 启用状态监控 access_log off; # 禁用访问日志 allow 127.0.0.1; # 只允许本机访问 deny all; # 拒绝其他所有访问 }测试命令curllocalhost/status6.2 中文乱码6.3 虚拟主机配置# 创建网站目录mkdir/www1/echoweb1/www1/index.html# 配置虚拟主机vim/usr/local/nginx/conf/nginx.confvim /etc/hostscurl www.example.com6.4 HTTPS 配置# 生成 SSL 证书cd/etc/pki/tls/certsmakecert.pem# 复制证书到 Nginx 配置目录,将pem文件移动到跟nginx.conf一个路径cpcert.pem /usr/local/nginx/conf/# 配置 Nginxvim/usr/local/nginx/conf/nginx.confnginx-sreload测试 HTTPScurlhttps://www.example.com-k6.4 HTTP 重定向到 HTTPSserver { listen 80; server_name www1.westos.org; rewrite ^/(.*)$ https://www1.westos.org/$1 permanent; }重新加载然后测试6.5 路径重定向# 将 www.westos.org/bbs 重定向到 bbs.westos.org rewrite ^/bbs/(.*)$ http://bbs.westos.org/$1 permanent;mkdir/web2cd/web2echowww.westos.orgindex.htmlmkdir/bbsechobbs.westos.org/bbs/index.html6.6 防盗链配置配置server2上的apache服务盗链server1上的图片配置域名解析vim /etc/hostsvim index.htmllocation ~ \.(jpg|png)$ { root /www; valid_referers none blocked www.westos.org; if ($invalid_referer) { # return 403; # 直接返回 403 rewrite ^/ http://bbs.westos.org/daolian.jpg; # 重定向到指定图片 } }7. HTTP 状态码速查表状态码范围类别说明常见示例1xx (100-199)信息提示临时响应极少遇到100 Continue大文件上传2xx (200-299)成功请求已成功处理✅ 200 OK正常返回3xx (300-399)重定向需要进一步操作 301永久重定向 302临时重定向4xx (400-499)客户端错误问题出在请求方 403权限不足 404文件不存在 401需要认证5xx (500-599)服务器错误问题出在后端 502 Bad Gateway后端不可达 504 Gateway Timeout响应超时 500 Internal Server Error后端代码错误8. 故障排查技巧检查配置文件语法nginx-t查看错误日志tail-f/usr/local/nginx/logs/error.log测试负载均衡# 使用 ab 工具测试ab-c10-n100http://www.westos.org/# 查看后端服务器访问日志tail-f/var/log/nginx/access.log验证模块加载nginx-V21|grepsticky检查端口监听netstat-tlnp|grepnginx