Oamc

Nginx 部署与反向代理

本页目录

场景

一台 Linux 上要让几个内部服务共用 80/443,或者给后端应用加一层 TLS。

前置条件

  • 域名解析指向这台机器
  • 后端服务已经在本地端口上跑起来
  • 防火墙/安全组放行 80、443

配置

# 安装
dnf install -y nginx          # CentOS / 麒麟
apt install -y nginx          # Ubuntu / Debian

# 反代配置
cat >/etc/nginx/conf.d/app.conf <<'EOF'
server {
    listen 80;
    server_name kb.example.com;

    client_max_body_size 100m;

    location / {
        proxy_pass http://127.0.0.1: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 /ws/ {
        proxy_pass http://127.0.0.1:8080;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
    }
}
EOF

nginx -t
systemctl enable --now nginx
systemctl reload nginx

验证

nginx -t                          # 语法
curl -I http://127.0.0.1/         # 本机
curl -I -H "Host: kb.example.com" http://127.0.0.1/
tail -f /var/log/nginx/error.log

回滚

rm /etc/nginx/conf.d/app.conf
nginx -t && systemctl reload nginx

坑

  • client_max_body_size 不配,上传稍大一点就 413。
  • proxy_pass http://127.0.0.1:8080; 结尾有没有 / 决定路径怎么拼,别想当然。
  • 后端拿到的客户端 IP 全是 127.0.0.1,除非把 X-Forwarded-For 传下去并在后端信任。
  • SELinux 开着时,反代连接被拦,setsebool -P httpd_can_network_connect 1。
  • 改完配置一定要先 nginx -t,直接 reload 会把旧配置也带挂。
  • 证书路径写错时 nginx 起不来,systemctl status nginx 会给出具体路径。