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

NGINX重写规则问题:捕获URL末尾部分并匹配开头

NGINX多级目录URL重定向规则优化

需求回顾

原规则仅能匹配product-category后直接跟单级目录的URL,无法处理中间存在多层父目录的情况,需要修改规则以提取任意层级路径下的最后一级目录名,并统一重定向到/shop/?categories[]=最后一级目录名。

解决方案1:使用rewrite指令(推荐)

NGINX官方建议尽量避免在server块中使用if,使用rewrite更符合最佳实践:

rewrite ^/product-category/.*/([^/]+)/$ /shop/?categories[]=$1 permanent;

解决方案2:使用if+return(兼容原写法)

如果习惯原有的if结构,可调整正则表达式实现需求:

if ($request_uri ~ ^/product-category/.*/([^/]+)/$) {
    return 301 /shop/?categories[]=$1;
}

正则表达式说明

  • ^/product-category/:匹配URL开头固定的/product-category/前缀
  • .*/:贪婪匹配任意字符直到倒数第二个/(跳过所有中间层级目录)
  • ([^/]+):捕获最后一级目录名,[^/]+表示匹配一个或多个非/的字符
  • /:匹配URL结尾的目录分隔符

验证示例

对于以下URL:

  • https://example.com/product-category/parent/cat-1/
  • https://example.com/product-category/gparent/parent/cat-1/
  • https://example.com/product-category/distant-relative/gparent/parent/cat-1/

上述规则都会将其重定向到:
https://example.com/shop/?categories[]=cat-1

额外提示

如果需要忽略URL大小写(比如兼容Product-Category这类写法),可调整规则为:

# if写法忽略大小写
if ($request_uri ~* ^/product-category/.*/([^/]+)/$) {
    return 301 /shop/?categories[]=$1;
}

# rewrite写法忽略大小写
rewrite ~* ^/product-category/.*/([^/]+)/$ /shop/?categories[]=$1 permanent;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 02:18:29