Nginx location前缀rewrite配置困惑:仅匹配/sandbox/test的问题
Nginx配置问题解决
问题根源分析
- location前缀匹配特性:你使用的
location /sandbox是前缀匹配规则,Nginx会匹配所有以/sandbox开头的URI,包括/sandbox2/test(因为它的路径开头是/sandbox),这就是错误捕获非目标路径的原因。 - rewrite匹配规则误解:你误以为
location块内的rewrite会匹配去掉前缀后的剩余URI,但实际上默认是匹配完整的请求URI。所以rewrite ^/test$ /script.php last;无法匹配/sandbox/test(完整URI是/sandbox/test,而非/test),导致返回404。
解决方案
方案1:限制location匹配范围(推荐)
将location修改为带末尾斜杠的前缀匹配,这样只会匹配以/sandbox/开头的URI,自动排除/sandbox2/test这类路径。如果需要处理/sandbox本身(不带斜杠的请求),可单独添加精确匹配块:
# 处理所有以/sandbox/开头的请求 location /sandbox/ { # 仅匹配/sandbox/test rewrite ^/sandbox/test$ /script.php last; # 此处可添加其他针对/sandbox前缀的rewrite规则 } # 处理/sandbox本身的请求(可选) location = /sandbox { # 写入针对/sandbox的规则,比如跳转或返回内容 }
方案2:保留原location前缀,调整rewrite规则
若不想修改location结构,直接在原location /sandbox内使用匹配完整URI的rewrite规则,同时保留添加其他规则的空间:
location /sandbox { # 仅匹配完整的/sandbox/test URI rewrite ^/sandbox/test$ /script.php last; # 此处可添加其他针对/sandbox前缀的rewrite规则,比如匹配/sandbox/xxx等 }
这种方式下,虽然location仍会命中/sandbox2/test,但rewrite规则仅对/sandbox/test生效,/sandbox2/test进入该location后不会被改写,会继续走后续规则或返回404(若无其他匹配)。
方案3:用正则location精确控制匹配范围
如果需要更灵活的匹配逻辑,可使用正则location确保只匹配/sandbox或/sandbox/开头的路径:
location ~ ^/sandbox($|/) { rewrite ^/sandbox/test$ /script.php last; # 其他针对/sandbox前缀的规则 }
正则^/sandbox($|/)表示匹配以/sandbox结尾(即/sandbox本身),或/sandbox/开头的所有URI,可完美排除/sandbox2类路径。
内容的提问来源于stack exchange,提问作者Marek Barta
相关产品推荐
相关产品推荐

