侧边栏壁纸
博主头像
程序员の小站博主等级

行动起来,活在当下

  • 累计撰写 51 篇文章
  • 累计创建 35 个标签
  • 累计收到 0 条评论

目 录CONTENT

文章目录

Nginx--前后端分离项目配置文件

Administrator
2025-06-23 / 0 评论 / 0 点赞 / 0 阅读 / 5379 字
温馨提示:
本文最后更新于 2025-06-23,若内容或图片失效,请留言反馈。部分素材来自网络,若不小心影响到您的利益,请联系我们删除。
worker_processes  1;

events {
    worker_connections  1024;
}

http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on; 
    keepalive_timeout  65;
    
    server {
        listen       80;
        server_name  localhost;  # 替换为你的域名或IP

        # 静态资源服务 (base URL: /financial)
        location /financial/ {
            alias /opt/nginx/html/view/;  # 注意:结尾必须有斜杠
            index index.html;
            
            # 处理前端路由刷新404问题
            try_files $uri $uri/ /financial/index.html;
        }

        # API代理配置 (保留/financial/api前缀)
        location /financial/api/ {
            proxy_pass http://127.0.0.1:8081;  # 注意结尾斜杠
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            
            # 保留原始请求路径(不修改/financial/api前缀)
            proxy_set_header X-Original-URI $request_uri;
        }

        # 可选:直接访问根路径时重定向到/financial
        location = / {
            return 301 /financial;
        }

        # 错误处理
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    }
}

location 和 proxy_pass

Location指令末尾的斜杠

location /financial/api/ { … } 只匹配 URI 中以 /financial/api/ 开头的请求(例如 /financial/api/test),而不会匹配恰好为 /financial/api 的请求。location /financial/api { … } 既能匹配恰好等于 /financial/api 的请求,也能匹配以 /financial/api 为前缀的(例如 /financial/api/test)。

proxy_pass指令末尾的斜杠

当 proxy_pass 中包含 URI 部分(即 URL 后面有一个斜杠,如 http://127.0.0.1:8081/)时,Nginx 会用该 URI 替换 location 匹配到的那一部分;如果省略(如 http://127.0.0.1:8081),则直接将原始请求的完整 URI(通常包括匹配的前缀)追加到 upstream 地址后。

下面通过几个例子说明假设客户端请求:/financial/api/test

配置写法 说明 转发到后端的URL
location /financial/api/ {
proxy_pass http://127.0.0.1:8081;
}
使用了location带尾斜杠,
proxy_pass无URI部分,不做替换,直接追加整个请求的URI
http://127.0.0.1:8081/financial/api/test
location /financial/api/ {
proxy_pass http://127.0.0.1:8081/;
}
location带尾斜杠,proxy_pass带尾斜杠。此时匹配的financial/api被替换为proxy_pass后的/ http://127.0.0.1:8081/test
location /financial/api {
proxy_pass http://127.0.0.1:8081;
}
location没有尾斜杠匹配前缀financial/api;proxy_pass无URI部分,完整器ing求URI被追加 http://127.0.0.1:8081/financial/api/test
location /financial/api {
proxy_pass http://127.0.0.1:8081/;
}
location没有尾斜杠;proxy_pass带尾斜杠,将匹配financial/api替换为/ http://127.0.0.1:8081/test

总结

location 的写法影响匹配范围

  • /financial/api/ 只匹配需要后面至少有一个斜杠的请求;
  • /financial/api 除了匹配带额外路径的情况,还能匹配完全一致的路径。

proxy_pass 后是否跟有斜杠

  • 无尾斜杠时,上游会接收到包含 location 前缀的完整 URI;
  • 有尾斜杠时,会将 location 匹配的那一段“剥离”,只转发剩余部分。
0

评论区