常用命令

nginx -t                 # 检查配置
systemctl reload nginx   # 热加载,不中断连接
systemctl restart nginx

反代后端

后端跑在本机某个端口(如 127.0.0.1:5000),Nginx 对外暴露 80/443。

server {
    listen 80;
    server_name api.example.com;

    client_max_body_size 20m;   # 上传大小,默认 1m

    location / {
        proxy_pass http://127.0.0.1:5000;
        proxy_http_version 1.1;
        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;
        proxy_set_header Connection "";
    }
}

HTTPS

证书:

server {
    listen 80;
    server_name example.com;
    return 301 https://$host$request_uri;
}

server {
    listen 443 ssl http2;
    server_name example.com;

    ssl_certificate     /etc/letsencrypt/live/example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
}

部署单页应用

Vue/React 打包后是静态文件。History 路由必须把所有路径回退到 index.html

server {
    listen 80;
    server_name example.com;
    root /var/www/app/dist;
    index index.html;

    gzip on;
    gzip_types text/plain text/css application/json application/javascript;

    # 路由模式必须的
    location / {
        try_files $uri $uri/ /index.html;
    }
}