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

Nginx正则重定向配置:仅允许含/news/的URL保留/amp/后缀

解决Nginx AMP重定向的例外规则需求

Got it, let's tweak your Nginx configuration to handle this scenario exactly how you want. The core idea is to set up an exception first for /news/ paths ending with /amp/, then apply your original redirect rule to all other /amp/-ending URLs. Since Nginx processes rules in order, putting the exception first ensures it gets matched before the general redirect.

Here's the exact code you can add to your server block:

# 例外规则:匹配/news/路径下以/amp/结尾的请求,直接交给后端处理(不执行重定向)
location ~* ^/news/.+/amp/$ {
    # 替换成你处理正常/news/请求的配置即可
    # 比如WordPress环境常用的配置:
    try_files $uri $uri/ /index.php?$args;
}

# 通用规则:所有其他以/amp/结尾的URL,重定向到移除amp/后的地址
location ~* /amp/$ {
    rewrite ^(.*)/amp/$ $1 permanent;
}

关键细节说明:

  • 第一个location用正则精准匹配:以/news/开头、中间包含任意内容、最后以/amp/结尾的URL,确保只有新闻类的AMP地址跳过重定向。
  • ~*表示忽略大小写匹配(虽然你的URL大概率是小写,但这样更健壮)。
  • 第二个location会捕获所有未被例外规则命中的/amp/结尾URL,执行永久重定向到去掉amp/的地址。

注意要把这些规则放在服务器块里其他通用location规则之前(比如你的主PHP处理规则),保证优先级正确。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 04:25:48