插件窝 干货文章 Nginx服务器如何搭建反向代理

Nginx服务器如何搭建反向代理

Nginx proxy server backend 412    来源:    2025-04-25

Nginx反向代理搭建指南

反向代理是Nginx最常用的功能之一,它可以将客户端请求转发到后端服务器,隐藏后端服务器细节,实现负载均衡、安全防护等功能。以下是详细的搭建步骤:

1. 安装Nginx

首先确保已安装Nginx:

# Ubuntu/Debian
sudo apt update
sudo apt install nginx

# CentOS/RHEL
sudo yum install epel-release
sudo yum install nginx

# 启动Nginx
sudo systemctl start nginx
sudo systemctl enable nginx

2. 基本反向代理配置

编辑Nginx配置文件(通常在/etc/nginx/nginx.conf/etc/nginx/conf.d/default.conf):

server {
    listen 80;
    server_name yourdomain.com;  # 替换为你的域名或IP

    location / {
        proxy_pass http://backend_server_ip:backend_port;  # 后端服务器地址
        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_connect_timeout 60s;
        proxy_send_timeout 60s;
        proxy_read_timeout 60s;
    }
}

3. 高级配置选项

负载均衡

upstream backend_servers {
    server backend1.example.com:8080 weight=3;  # 权重3
    server backend2.example.com:8080;           # 默认权重1
    server backup.example.com:8080 backup;       # 备用服务器

    # 负载均衡策略
    # least_conn;  # 最少连接
    # ip_hash;     # IP哈希
}

server {
    listen 80;
    server_name yourdomain.com;

    location / {
        proxy_pass http://backend_servers;
        # 其他proxy设置...
    }
}

WebSocket代理

location /wsapp/ {
    proxy_pass http://ws_backend;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";
}

SSL终止

server {
    listen 443 ssl;
    server_name yourdomain.com;

    ssl_certificate /path/to/cert.pem;
    ssl_certificate_key /path/to/key.pem;

    location / {
        proxy_pass http://backend_server;
        # 其他proxy设置...
    }
}

4. 缓存配置

proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=my_cache:10m inactive=60m use_temp_path=off;

server {
    # ...

    location / {
        proxy_cache my_cache;
        proxy_cache_valid 200 302 10m;
        proxy_cache_valid 404 1m;
        proxy_cache_use_stale error timeout updating http_500 http_502 http_503 http_504;

        proxy_pass http://backend_server;
    }
}

5. 测试与重载配置

# 测试配置语法
sudo nginx -t

# 重载配置
sudo systemctl reload nginx

6. 常见问题排查

  1. 502 Bad Gateway:检查后端服务器是否运行,网络是否通畅
  2. 连接超时:调整proxy_connect_timeout等超时设置
  3. 头部信息丢失:确保正确设置了proxy_set_header指令
  4. 性能问题:考虑启用缓存或调整缓冲区大小

安全建议

  1. 限制访问IP:
location / {
    allow 192.168.1.0/24;
    deny all;
    # ...
}
  1. 禁用不必要的HTTP方法:
if ($request_method !~ ^(GET|HEAD|POST)$ ) {
    return 405;
}
  1. 定期更新Nginx版本以修复安全漏洞

以上配置可根据实际需求进行调整组合。对于生产环境,建议进行充分的测试和性能调优。