Nginx 的 location
指令用于匹配请求 URI,是配置中最重要和最常用的指令之一。以下是 location 匹配的详细方法:
location [modifier] pattern {
# 配置指令
}
Nginx 支持以下几种匹配修饰符:
无修饰符 - 前缀匹配
location /images/ {
# 匹配以 /images/ 开头的 URI
}
=
精确匹配
location = /exact {
# 只匹配 /exact 这个 URI
}
~
区分大小写的正则匹配
location ~ \.php$ {
# 匹配以 .php 结尾的 URI,区分大小写
}
~*
不区分大小写的正则匹配
location ~* \.(jpg|jpeg|png|gif)$ {
# 匹配图片文件扩展名,不区分大小写
}
^~
优先前缀匹配
location ^~ /static/ {
# 匹配以 /static/ 开头的 URI,且优先于正则匹配
}
Nginx 按以下顺序检查 location 匹配:
=
精确匹配^~
优先前缀匹配~
和 ~*
正则匹配(按配置文件中出现的顺序)# 精确匹配
location = /favicon.ico {
access_log off;
expires 30d;
}
# 静态文件目录
location /static/ {
root /var/www;
expires max;
}
# PHP 文件处理
location ~ \.php$ {
fastcgi_pass unix:/var/run/php-fpm.sock;
include fastcgi_params;
}
# 图片文件缓存
location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
expires 7d;
add_header Cache-Control "public";
}
# 禁止访问隐藏文件
location ~ /\. {
deny all;
}
^~
提高性能可以使用 echo
模块或日志来调试 location 匹配:
location /test {
echo "This is test location";
}
# 或者在日志中记录匹配的 location
log_format location_debug '$request_uri - $uri - $document_uri - $request_filename';
理解 Nginx 的 location 匹配规则对于配置高效、准确的服务器行为至关重要。