nginx反向代理配置详解
2025-03-05
136
参考资料
nginx反向代理配置详解
基础配置
server { listen 80; server_name example.com; location / { proxy_pass http://backend_server; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } }
listen
: 监听端口server_name
: 域名或IPlocation
: 匹配请求路径proxy_pass
: 指定后端服务地址proxy_set_header
: 设置请求头传递信息
常用参数
proxy_connect_timeout
: 后端连接超时时间(默认60s)proxy_read_timeout
: 读取后端响应超时时间(默认60s)proxy_send_timeout
: 发送请求到后端的超时时间(默认60s)proxy_buffering off
: 关闭响应缓冲(适用于实时流)
SSL配置
server { listen 443 ssl; server_name example.com; ssl_certificate /path/to/cert.pem; ssl_certificate_key /path/to/key.pem; location / { proxy_pass http://backend_server; # 保持基础配置中的header设置 } }
WebSocket支持
location /ws/ { proxy_pass http://websocket_server; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; }
负载均衡
upstream backend { server 192.168.1.10:8080; server 192.168.1.11:8080; server 192.168.1.12:8080; } server { location / { proxy_pass http://backend; } }
缓存控制
proxy_cache_path /data/nginx/cache levels=1:2 keys_zone=my_cache:10m; location / { proxy_cache my_cache; proxy_cache_valid 200 302 10m; proxy_cache_valid 404 1m; }
检查配置并重载
nginx -t # 验证配置 nginx -s reload # 重载配置
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。