You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Nginx正则匹配多站点出现重定向循环问题求助

解决Nginx正则匹配含"sibe"站点时的重定向循环问题

嘿,我来帮你捋清楚这个问题!你之前单个精准匹配location的配置没问题,但换成正则匹配后出现循环错误,核心原因是请求重定向后的index.php路径又被你的正则location重新匹配到了,导致Nginx反复处理同一个请求,陷入无限循环。

错误原因拆解

你的正则配置:

location ~ /([a-z]*sibe[a-z]*)/ {
    set $subdomain $1;
    alias /var/www/$subdomain/;
    try_files $uri $uri/ /$subdomain/index.php;
}

当请求/fwsibe/acesso时,try_files找不到对应文件,会重定向到/fwsibe/index.php。但这个新请求的路径里包含sibe,又会被你的正则规则匹配到,再次进入同一个location处理。Nginx反复执行这个流程,就会抛出rewrite or internal redirection cycle错误。

两种可行的解决方案

方案1:分离静态文件与PHP请求处理

把PHP请求交给专门的location处理,避免正则location拦截PHP请求:

# 优先处理所有PHP请求(确保这个location在正则location之前)
location ~ \.php$ {
    root /var/www;
    fastcgi_pass unix:/run/php/php7.4-fpm.sock; # 根据你的PHP版本调整socket路径
    fastcgi_index index.php;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    include fastcgi_params;
}

# 匹配所有以含"sibe"前缀开头的路径
location ~ ^/([a-z]*sibe[a-z]*)/ {
    root /var/www; # 用root替代alias,路径逻辑更清晰稳定
    try_files $uri $uri/ /$1/index.php;
}

原理:当重定向到/fwsibe/index.php时,会被.php的location优先匹配并处理,不会再进入正则location,彻底切断循环链。

方案2:使用命名location做重定向

如果想保留alias配置,可以用命名location来执行最终重定向,并用last指令让Nginx重新匹配规则:

# 匹配含"sibe"前缀的路径
location ~ ^/([a-z]*sibe[a-z]*)/ {
    alias /var/www/$1/;
    try_files $uri $uri/ @rewrite_to_index;
}

# 命名location处理重定向
location @rewrite_to_index {
    rewrite ^/([a-z]*sibe[a-z]*)/.*$ /$1/index.php last;
}

# PHP请求处理location
location ~ \.php$ {
    root /var/www;
    fastcgi_pass unix:/run/php/php7.4-fpm.sock;
    fastcgi_index index.php;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    include fastcgi_params;
}

原理:try_files找不到文件时,跳转到@rewrite_to_index执行重定向,last指令会让Nginx终止当前location的处理,重新匹配新的请求路径,这样.php的location就能接手处理了。

额外注意事项

  • 正则表达式要精准:用^/([a-z]*sibe[a-z]*)/确保只匹配前缀含sibe的路径,避免匹配中间带sibe的无关路径。
  • Nginx的location匹配顺序:正则location是按定义顺序匹配的,所以一定要把.php的location放在正则location前面,确保PHP请求被优先处理。

内容的提问来源于stack exchange,提问作者mayconfsbrito

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:05:17