Nginx代理配置详解
1. 正向代理
server {
listen 80;
resolver 8.8.8.8; # DNS解析服务器
location / {
proxy_pass http://$http_host$request_uri; # 转发客户端请求
}
}
2. 反向代理
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;
}
}
3. 常用指令
proxy_pass
:定义后端服务器地址(如http://localhost:3000
)。
proxy_set_header
:修改请求头(如传递真实客户端IP)。
proxy_redirect
:重定向响应头中的URL。
proxy_buffer_size
:设置代理缓冲区大小。4. 负载均衡
upstream backend {
server backend1.example.com;
server backend2.example.com;
}
server {
location / {
proxy_pass http://backend;
}
}
weight
:权重分配。
ip_hash
:基于IP的会话保持。
least_conn
:最少连接数优先。
5. 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;
proxy_set_header X-Forwarded-Proto https;
}
}
6. WebSocket代理
location /ws {
proxy_pass http://backend_ws;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}
7. 缓存配置
proxy_cache_path /path/to/cache levels=1:2 keys_zone=my_cache:10m;
location / {
proxy_cache my_cache;
proxy_pass http://backend;
}
配置文件位置
/etc/nginx/nginx.conf
/etc/nginx/sites-available/
/etc/nginx/sites-enabled/
重载配置
sudo systemctl reload nginx