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