Nginx的location指令是配置中最重要也最灵活的部分之一,它决定了如何处理不同的请求URI。下面我将通过实例详细分析location的各种配置方式。
location [修饰符] 匹配模式 {
# 配置指令
}
=
^~
~
或 ~*
(区分大小写/不区分大小写)location = /exact/match {
# 只有当请求URI完全等于"/exact/match"时才会匹配
return 200 "Exact match found";
}
location ^~ /static/ {
# 匹配以/static/开头的URI,且不检查正则表达式
root /var/www;
}
location ~ \.(jpg|png|gif)$ {
# 匹配以.jpg、.png或.gif结尾的URI,区分大小写
expires 30d;
access_log off;
}
location ~* \.(js|css)$ {
# 匹配以.js或.css结尾的URI,不区分大小写
expires 7d;
add_header Cache-Control "public";
}
location /images/ {
# 匹配以/images/开头的URI
root /data;
}
server {
listen 80;
server_name example.com;
# 1. 精确匹配优先
location = /login {
proxy_pass http://auth_server;
}
# 2. 静态文件前缀匹配
location ^~ /static/ {
root /var/www/static;
expires max;
access_log off;
}
# 3. PHP文件处理
location ~ \.php$ {
fastcgi_pass unix:/var/run/php-fpm.sock;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
}
# 4. 图片文件缓存
location ~* \.(jpg|jpeg|png|gif|ico|svg)$ {
expires 30d;
add_header Cache-Control "public";
}
# 5. 默认处理
location / {
try_files $uri $uri/ /index.php?$query_string;
}
}
症状:预期的location没有被匹配到
解决方案: - 确保精确匹配(=)放在最前面 - 使用^~避免正则检查 - 调整location顺序,Nginx按特定顺序检查location
症状:正则location没有匹配预期的URI
解决方案: - 检查正则语法是否正确 - 确认是否使用了正确的修饰符(~或~*) - 使用在线正则测试工具验证表达式
症状:文件路径不正确
解决方案: - root会将location路径附加到指定目录后 - alias会替换location路径为指定目录
location /images/ {
root /data; # 最终路径: /data/images/
}
location /img/ {
alias /data/images/; # 最终路径: /data/images/
}
通过合理配置location,可以显著提高Nginx的性能和灵活性。