Nginx Rewrite规则配置求助:替换路径并移除指定虚词
Nginx Rewrite规则修正方案
你的原有配置存在几个关键问题:
location = /posts是精确匹配,仅能匹配/posts这一个路径,无法覆盖/posts/2021/10/...这类带年份、月份的子路径请求- Rewrite语法逻辑倒置:Rewrite指令的第一个参数是需要匹配的正则表达式,第二个才是替换目标,你把两者写反了
- 正则表达式语法错误:捕获组
$1应出现在匹配正则中而非替换目标;单词边界在Nginx正则里需写为\b;正则结构混乱,未正确分组需要保留的内容
正确配置示例
以下配置可实现需求:将/posts替换为/news,保留年份、月份两级路径,并移除指定虚词(覆盖开头、中间、结尾的虚词场景):
server { # 其他服务器配置(如listen、root等) # 第一步:替换posts为news,捕获并保留年份、月份及剩余路径 rewrite ^/posts/(\d{4})/(\d{2})/(.*)$ /news/$1/$2/$3; # 第二步:移除路径中间的"-虚词-"结构(如-for- → 空,tips-for-working → tips-working) rewrite ^(/news/\d{4}/\d{2}/)(.*)$ $1${2//-(a|an|and|as|at|before|but|by|for|from|is|in|into|like|of|off|on|onto|or|per|since|than|the|this|that|to|up|via|with)-//} last; # 第三步:移除路径开头的"虚词-"结构(如a-test → test) rewrite ^(/news/\d{4}/\d{2}/)(a|an|and|as|at|before|but|by|for|from|is|in|into|like|of|off|on|onto|or|per|since|than|the|this|that|to|up|via|with)-(.*)$ $1$3 last; # 第四步:移除路径结尾的"-虚词"结构(如test-for → test) rewrite ^(/news/\d{4}/\d{2}/)(.*)-(a|an|and|as|at|before|but|by|for|from|is|in|into|like|of|off|on|onto|or|per|since|than|the|this|that|to|up|via|with)$ $1$2 last; # 其他配置... }
配置说明
- 第一步:精准匹配
/posts/年份/月份/剩余路径格式的请求,将posts替换为news,同时保留年份、月份和后续路径内容 - 第二步:使用Nginx变量替换语法
${var//pattern/replacement},全局移除剩余路径中-虚词-的结构,比如将cyber-security-tips-for-working-from-home中的-for-和-from-直接移除,得到cyber-security-tips-working-home - 第三步:处理路径开头的虚词前缀,比如将
a-test-case转换为test-case - 第四步:处理路径结尾的虚词后缀,比如将
test-case-for转换为test-case
如果你的Nginx版本不支持变量替换语法,可改用多次Rewrite逐个移除虚词(适合旧版Nginx):
# 替代第二步:逐个移除中间的虚词 rewrite ^(/news/\d{4}/\d{2}/)(.*)-for-(.*)$ $1$2-$3 last; rewrite ^(/news/\d{4}/\d{2}/)(.*)-from-(.*)$ $1$2-$3 last; rewrite ^(/news/\d{4}/\d{2}/)(.*)-a-(.*)$ $1$2-$3 last; # 其他虚词按此格式依次添加...
内容的提问来源于stack exchange,提问作者ginobambino
相关产品推荐
相关产品推荐

