NGINX实现URL静默重写至二级子目录的循环问题求助
解决NGINX目录映射循环问题
问题回顾
服务器目录结构为:
/var/www/<user>/<user>/
当前需访问 https://<host>/<user>/<user> 才能获取文件,期望实现访问 https://<host>/<user>/ 时,后端自动静默映射到二级子目录,但原有规则触发了重写循环。
解决方案
方案一:使用 alias 精准映射用户根目录
# 处理用户根目录请求(如 https://<host>/user/) location ~ ^/([^/]+)/$ { alias /var/www/$1/$1/; index index.html; } # 处理用户目录下的文件/子路径请求(如 https://<host>/user/file.html) location ~ ^/([^/]+)/(.*)$ { root /var/www/$1; try_files /$1/$2 /$1/$2/index.html =404; }
方案二:用 rewrite break 终止重写循环
location ~ ^/([^/]+)/$ { # 内部重写至二级子目录,break 终止后续规则匹配 rewrite ^/([^/]+)/$ /$1/$1/ break; root /var/www; index index.html; } location ~ ^/([^/]+)/(.*)$ { root /var/www; try_files /$1/$2 /$1/$2/index.html =404; }
原规则循环原因分析
原有规则 location ~ ^/(.*)/(.*)$ 的正则过于宽泛,(.*) 会匹配包含 / 的字符串。当请求 /user/file.html 时,try_files $uri /$1/$uri/index.html /$1/$uri 会生成 /user//user/file.html 这样的路径,该路径再次被同一条 location 规则匹配,进而重复执行重写逻辑,最终陷入循环。
新方案通过 [^/]+ 限制第一个捕获组仅匹配用户名(不含 /),避免了重写后的路径再次触发同一条规则,从根源上解决了循环问题。
内容的提问来源于stack exchange,提问作者CMP
相关产品推荐
相关产品推荐

