nginx location配置段
location 配置段定义 URL 路径的匹配规则,决定请求的处理方式。
基本语法
nginx
location [修饰符] 路径 {
# 配置指令
}
修饰符类型
| 修饰符 | 匹配类型 | 说明 |
|---|---|---|
| 无 | 前缀匹配 | 以指定路径开头 |
= | 精确匹配 | 完全匹配路径 |
~ | 正则匹配 | 区分大小写 |
~* | 正则匹配 | 不区分大小写 |
^~ | 前缀匹配 | 匹配后停止正则搜索 |
匹配优先级
nginx
= → ^~ → 按文件顺序正则 → 按文件顺序前缀 → /
精确匹配 > 前缀匹配(^~) > 正则匹配 > 普通前缀匹配 > 通用匹配 /
匹配示例
精确匹配
nginx
location = /favicon.ico {
log_not_found off;
access_log off;
}
仅匹配 /favicon.ico,不匹配 /favicon.ico?version=1。
前缀匹配
nginx
location /images/ {
root /data;
}
匹配 /images/logo.png、/images/icons/arrow.png 等。
优先前缀匹配
nginx
location ^~ /images/ {
root /data;
}
匹配后不再搜索正则 location。
正则匹配
nginx
# 区分大小写
location ~ \.php$ {
fastcgi_pass 127.0.0.1:9000;
}
# 不区分大小写
location ~* \.(jpg|jpeg|png|gif)$ {
expires 30d;
}
完整匹配示例
nginx
server {
server_name example.com;
# 1. 精确匹配(最高优先级)
location = / {
return 200 "home";
}
# 2. 优先前缀匹配
location ^~ /static/ {
root /data;
expires 30d;
}
# 3. 正则匹配
location ~* \.(css|js)$ {
root /data/assets;
expires 7d;
}
# 4. 普通前缀匹配
location /api/ {
proxy_pass http://backend;
}
# 5. 通用匹配(最低优先级)
location / {
try_files $uri $uri/ /index.html;
}
}
嵌套 location
nginx
location / {
location ~ \.php$ {
fastcgi_pass 127.0.0.1:9000;
}
}
try_files
按顺序尝试文件:
nginx
location / {
try_files $uri $uri/ /index.html;
}
- 尝试
$uri文件 - 尝试
$uri/目录 - 返回
/index.html
重定向
nginx
# 内部重定向
location /old/ {
rewrite ^/old/(.*)$ /new/$1 permanent;
}
# 返回状态码
location /deprecated/ {
return 410;
}
常用 location 配置
静态资源
nginx
location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
root /data/static;
expires 30d;
access_log off;
}
PHP 处理
nginx
location ~ \.php$ {
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
拒绝访问
text
location ~ /\.ht {
deny all;
}
注意事项
- 正则匹配按配置文件顺序执行,先匹配到先生效
^~前缀匹配成功后不再搜索正则- location 内的配置继承自 server 段
- 避免 location 路径与 root/alias 组合错误
要点总结
- location 修饰符:=(精确)、^~(优先前缀)、~(正则区分大小写)、~*(正则不区分)
- 匹配优先级:精确 > 优先前缀 > 正则 > 普通前缀 > 通用
- 正则匹配按配置顺序执行,前缀匹配不按顺序
- try_files 按顺序尝试文件,适用于 SPA 路由
- 静态资源建议使用 ~* 正则 + expires 缓存
- 敏感目录使用 deny all 拒绝访问
📝 发现内容有误?点击此处直接编辑