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

Nginx博客子域名重定向规则配置后循环跳转问题求助

Nginx重定向循环问题分析与解决

首先,你遇到的循环跳转核心原因不是规则顺序,而是两段规则本身存在逻辑错误,先逐个拆解问题:

第一段规则的致命错误

server_name 字段只能用来匹配域名(比如www.qwerty.com),不能包含URI路径。你把完整路径www.example.com/blog/category/educator-blog/写在server_name里,这段规则根本不会被Nginx触发,相当于完全无效。

第二段规则的循环元凶

你在blog.qwerty.com的配置里,写了把/educator(.*)重定向回www.qwerty.com/blog/category/educator-blog/$1的规则——这直接导致了循环:
当用户访问www.qwerty.com/blog/category/educator-blog/时,假设你有正确规则跳转到blog.qwerty.com/educator/,但这段反向重定向又会把请求打回原域名,一来一回就形成了无限循环。

规则顺序的实际影响

规则顺序确实会影响Nginx的执行结果:

  • 多个server块会按server_name的匹配优先级(精确匹配>通配符>正则)选择执行;
  • 同一个server块内的location,前缀匹配按最长路径匹配,正则匹配按书写顺序匹配第一个符合的;
  • 同一个location内的rewrite规则,会按从上到下的顺序依次执行。
    但你当前的问题根源是规则逻辑错误,不是顺序问题。

正确的配置写法

1. 在www.qwerty.com的server块中添加重定向规则

负责把www.qwerty.com/blog/category/educator-blog/及其子路径跳转到blog.qwerty.com/educator/:

server {
    server_name www.qwerty.com;

    # 精确匹配目标路径,^~表示优先匹配该前缀
    location ^~ /blog/category/educator-blog/ {
        # 重写路径:把原路径中/blog/category/educator-blog/之后的部分保留,拼接到新域名的/educator/后
        rewrite ^/blog/category/educator-blog/(.*)$ $scheme://blog.qwerty.com/educator/$1 permanent;
    }

    # 其他www站点的原有配置...
}

2. 在blog.qwerty.com的server块中保留内部重写规则

删除反向重定向的规则,只保留业务需要的内部转发:

server {
    server_name blog.qwerty.com;

    location /educator {
        # 处理带参数的URL重写,last表示执行后重新匹配location
        rewrite ^/educator-categoryid-(.*)-productid-(.*).htm$ /educator.php?categoryid=$1&productid=$2 last;
        # 按需添加目录索引规则
        index index.php index.html;
    }

    # 其他blog站点的原有配置...
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 16:01:34