upstream
服务器组(后端地址),并在server
块中设置location /
的proxy_pass
指向该组,最后重载服务生效。反向代理的核心价值
- 安全防护:隐藏后端服务器IP,抵御DDoS攻击。
- 负载均衡:将流量分发到多台服务器,避免单点故障。
- SSL终端:集中处理HTTPS加密,减轻后端压力。 缓存**:加速静态资源访问,提升用户体验。
准备工作
-
环境要求
-
Linux服务器(Ubuntu/CentOS等)
-
域名(已解析到服务器IP)
-
安装Nginx:
# Ubuntu/Debian sudo apt update && sudo apt install nginx # CentOS/RHEL sudo yum install epel-release && sudo yum install nginx
-
-
基础目录结构
- 主配置文件:
/etc/nginx/nginx.conf
- 站点配置目录:
/etc/nginx/sites-available/
(推荐)或/etc/nginx/conf.d/
- 主配置文件:
Nginx反向代理配置步骤
场景示例
将访问 your-domain.com
的请求转发到本地端口 8080
的后端服务。
-
创建代理配置文件
sudo nano /etc/nginx/sites-available/reverse-proxy.conf
-
写入配置内容
server { listen 80; server_name your-domain.com; # 替换为你的域名 location / { proxy_pass http://localhost:8080; # 后端服务地址 proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } # 可选:静态文件缓存 location ~* .(jpg|css|js)$ { proxy_cache my_cache; proxy_pass http://localhost:8080; expires 30d; } }
-
启用配置并重启Nginx
sudo ln -s /etc/nginx/sites-available/reverse-proxy.conf /etc/nginx/sites-enabled/ sudo nginx -t # 测试配置语法 sudo systemctl restart nginx
高级配置技巧
-
负载均衡(分发到多台后端服务器)
upstream backend_servers { server 192.168.1.10:8080 weight=3; # 权重3 server 192.168.1.11:8080; server 192.168.1.12:8080 backup; # 备用服务器 } location / { proxy_pass http://backend_servers; }
-
HTTPS加密(使用Let’s Encrypt免费证书)
sudo apt install certbot python3-certbot-nginx sudo certbot --nginx -d your-domain.com
证书自动续期:
sudo certbot renew --dry-run
-
安全加固
- 限制IP访问:
location /admin { allow 192.168.1.100; deny all; proxy_pass http://localhost:8080; }
- 防止DDoS攻击:
limit_req_zone $binary_remote_addr zone=req_limit:10m rate=10r/s; location / { limit_req zone=req_limit burst=20; proxy_pass http://localhost:8080; }
- 限制IP访问:
验证与故障排除
-
测试反向代理是否生效
curl -I http://your-domain.com # 查看HTTP响应头
检查返回头中的
X-Proxy-Server
或后端应用日志确认请求来源。 -
常见错误排查
- 502 Bad Gateway:后端服务未启动或防火墙阻塞(检查
systemctl status 服务名
)。 - 403 Forbidden:Nginx权限不足(确保用户
www-data
或nginx
有权访问后端)。 - 地址冲突:端口占用(用
sudo ss -tulnp | grep :80
检查)。
- 502 Bad Gateway:后端服务未启动或防火墙阻塞(检查
-
日志分析
- Nginx访问日志:
/var/log/nginx/access.log
- 错误日志:
/var/log/nginx/error.log
- Nginx访问日志:
Apache反向代理方案(备选)
若使用Apache,启用模块并配置:
sudo a2enmod proxy proxy_http sudo nano /etc/apache2/sites-available/000-default.conf
加入配置:
<VirtualHost *:80> ServerName your-domain.com ProxyPass "/" "http://localhost:8080/" ProxyPassReverse "/" "http://localhost:8080/" </VirtualHost>
安全建议
- 定期更新Nginx:
sudo apt upgrade nginx
- 禁用不必要模块(如
autoindex
)。 - 使用WAF(如ModSecurity)防御SQL注入/XSS攻击。
- 配置防火墙:仅开放80/443端口。
反向代理不仅是技术优化手段,更是现代Web架构的基石,通过合理配置,可显著提升网站抗压能力与用户体验,建议结合监控工具(如Prometheus)持续观察流量变化,动态调整策略。
引用说明参考Nginx官方文档(nginx.org)、Let’s Encrypt指南(certbot.eff.org)及Mozilla安全配置标准(Mozilla SSL Config Generator),实践前请备份配置文件,生产环境建议在测试服务器验证。
原创文章,发布者:酷盾叔,转转请注明出处:https://www.kd.cn/ask/41159.html