Location 是 Nginx 配置中用于匹配请求 URI 并定义如何处理这些请求的指令块。它允许你根据 URL 路径的不同来应用不同的处理规则。
基本语法格式:
location [修饰符] 匹配模式 {
# 配置指令
}
location = /exact-path {
# 仅匹配 /exact-path
}
location /prefix {
# 匹配以 /prefix 开头的所有路径
}
location ~ \.php$ {
# 区分大小写的正则匹配.php结尾的路径
}
location ~* \.(jpg|jpeg|png)$ {
# 不区分大小写的正则匹配图片文件
}
location ^~ /images {
# 匹配以/images开头的最长路径,不检查正则表达式
}
Nginx 按以下顺序评估 location 块: 1. 精确匹配 (=) 2. 最长非正则前缀匹配 (^~) 3. 正则匹配 (~, ~*) 4. 普通前缀匹配
location /static/ {
alias /path/to/static/files/;
expires 30d;
access_log off;
}
location ~ \.php$ {
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
}
location /old-path {
return 301 /new-path;
}
location /user {
# 用户相关通用配置
location /user/profile {
# 用户个人资料特定配置
}
}
location /download {
if ($args ~* "file=(.*)") {
set $filename $1;
rewrite ^ /files/$filename? break;
}
}
location / {
error_page 404 /custom_404.html;
error_page 500 502 503 504 /custom_50x.html;
}
nginx -t
nginx -s reload
location /debug {
access_log /var/log/nginx/debug.log debug;
# 其他配置
}
通过以上步骤,你可以从零开始构建 Nginx 的 location 配置,根据实际需求灵活地处理各种 URL 请求。