Nginx 配置说明(含原请求与实际请求示例)

🧩 一、基础反向代理配置

location /api/ {
    proxy_pass http://127.0.0.1:8080/;
}

说明:

  • 当请求路径以 /api/ 开头时,转发到本地的 8080 端口。
  • 注意:proxy_pass 末尾的 / 会影响路径拼接方式。
原请求 实际请求
http://example.com/api/user http://127.0.0.1:8080/user

🧩 二、去掉末尾 / 的代理

location /api/ {
    proxy_pass http://127.0.0.1:8080;
}

说明:

  • 末尾不带 /,则原始请求路径会直接拼接在 proxy_pass 后面。
原请求 实际请求
http://example.com/api/user http://127.0.0.1:8080/api/user

🧩 三、前缀重写(rewrite)

location /napcat/ {
    rewrite ^/napcat/(.*)$ /$1 break;
    proxy_pass http://127.0.0.1:3000/;
}
原请求 实际请求
http://example.com/napcat/index.html http://127.0.0.1:3000/index.html

🧩 四、统一前缀代理(强制加上前缀)

location /napcat/ {
    proxy_pass http://127.0.0.1:3000/napcat/;
}
原请求 实际请求
http://example.com/napcat/index.html http://127.0.0.1:3000/napcat/index.html

🧩 五、子路径重定向(带正则)

location ~ ^/old/(.*)$ {
    rewrite ^/old/(.*)$ /new/$1 permanent;
}
原请求 实际请求
http://example.com/old/test 浏览器跳转到 http://example.com/new/test

🧩 六、子路径静态资源映射

location /static/ {
    alias /var/www/assets/;
}
原请求 实际访问文件
http://example.com/static/logo.png /var/www/assets/logo.png

🧩 七、反向代理 + WebSocket

location /ws/ {
    proxy_pass http://127.0.0.1:8081/;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";
}
原请求 实际请求
ws://example.com/ws/chat ws://127.0.0.1:8081/chat

🧩 八、前端 Vue/React 路由转发

location / {
    try_files $uri $uri/ /index.html;
}
原请求 实际请求文件
http://example.com/dashboard /index.html

🧩 九、跨域配置 (CORS)

location /api/ {
    add_header Access-Control-Allow-Origin *;
    add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS';
    add_header Access-Control-Allow-Headers '*';
    if ($request_method = OPTIONS) {
        return 204;
    }
    proxy_pass http://127.0.0.1:8080/;
}
原请求 实际请求
http://frontend.com/api/user http://127.0.0.1:8080/user

🧩 十、完整前后端分离项目示例

server {
    listen 80;
    server_name example.com;

    location / {
        root /var/www/frontend;
        try_files $uri $uri/ /index.html;
    }

    location /api/ {
        proxy_pass http://127.0.0.1:8080/;
    }
}
原请求 实际目标
http://example.com/ /var/www/frontend/index.html
http://example.com/api/user http://127.0.0.1:8080/user