Nginx 的 location 匹配规则
一、location 前缀匹配符号常用全集1.精确匹配优先级最高只匹配完全一模一样的路径。nginxlocation / { # 只匹配 /不匹配 /index.html、/xxx }速度最快适合首页、固定接口2.^~前缀匹配 禁止正则你现在用的匹配以 xxx 开头的路径匹配到就停止不再走后面的正则。nginxlocation ^~ /xxx/ { }优先级仅次于专门用来保护静态资源、独立目录不被正则抢走3.~区分大小写的正则匹配nginxlocation ~ \.php$ { }匹配以.php结尾的 URL。4.~*不区分大小写的正则匹配nginxlocation ~* \.(jpg|jpeg|png|css|js)$ { }匹配图片、CSS、JS大小写不敏感。5. 无前缀 普通前缀匹配nginxlocation /xxx/ { }前缀匹配但优先级低于正则容易被后面的~/~*覆盖你之前 404 就是因为这个6./通用匹配兜底nginxlocation / { }所有请求都能匹配最后兜底。二、优先级顺序必背从高到低精确匹配^~前缀匹配禁止正则~/~*正则匹配按配置文件先后顺序普通前缀匹配location /兜底三、除了匹配符常用核心指令1. root设置根目录路径拼接规则root 目录 请求路径nginxlocation /xxx/ { root D:/abc/cde; } # /xxx/xx → D:/abc/cde/xxx/xx2. alias直接替换路径不拼接 location 前缀nginxlocation /abc/assets/ { alias D:/aaa/html/abc/assets/; } # /abc/assets/xxx → D:/aaa/html/abc/assets/xxx适合路径不想被拼接的场景。3. try_files按顺序尝试文件找不到就跳转nginxtry_files $uri $uri/ /index.html;SPA 项目必备Vue/React。4. expires静态资源缓存nginxexpires 7d; expires max;5. proxy_pass反向代理nginxproxy_pass http://127.0.0.1:8080;6. return直接返回状态码或跳转nginxreturn 301 https://$host$request_uri; return 404;7. rewriteURL 重写nginxrewrite ^/old/(.*)$ /new/$1 permanent;8. add_header添加响应头跨域、缓存等nginxadd_header Access-Control-Allow-Origin *;9. index设置默认首页nginxindex index.html index.htm;10. error_page自定义错误页nginxerror_page 404 /404.html; error_page 500 502 503 /50x.html;四、你这个场景最适合的总结你现在的问题根源有全局正则比如匹配静态资源优先级比普通/abc/高导致 root 被篡改成D:\xxx\files所以你必须用location ^~ /abc/ { root D:/xxx/doc; index index.html; try_files $uri $uri/ /abc/index.html; }一般我们发现访问404的时候但是资源文件还存在那么可以去看一下error.log然后找到原因。之前原因就出现在全局设置了root然后直接定位到了另一个目录下这样看上去存在的资源在另一个目录里其实是不存在的。