.htaccess - 重定向所有 URL,但有一个例外

.htaccess - 重定向所有 URL,但有一个例外

我想将所有 URL 从一个域重定向到另一个域。一些旧 URL 有新的对应 URL,其中包含要重定向到的特定页面。所有其他 URL 都应重定向到新域的主页。

但我不想重新重定向sitemap.xml。所以我做了这样的例外(从这里):

RewriteCond %{REQUEST_URI} !^/sitemap.xml?$

但它不起作用。

这是我的完整代码:

RewriteEngine on

# exception for the sitemap:
RewriteCond %{REQUEST_URI} !^/sitemap.xml?$

# specific redirects:
Redirect 301 /old-page  https://www.new-domain.com/

# catch the rest:
RedirectMatch 301 ^/ https://www.new-domain.com/

有什么不对?

答案1

您混合使用了 mod_rewrite ( RewriteCond, RewriteRule) 和 mod_alias ( Redirect, RedirectMatch)。此处的 mod_rewriteRewriteCond指令不会执行任何操作。该指令仅适用于下一个RewriteRule指令。

因此,RewriteEngine是mod_rewrite并且与mod_alias无关。

您可以使用其中任意一种,但不能同时使用两种,因为处理顺序可能会导致意外冲突。

使用 mod_rewrite:

RewriteEngine on

# Specific redirects:
RewriteRule ^old-page$ https://www.new-domain.com/new-page [R=301,L]

# Catch the rest, except the sitemap:
RewriteRule !^sitemap\.xml$ https://www.new-domain.com/ [R=301,L]

请注意,匹配的 URL 路径RewriteRule 图案不以斜线开头。

你不需要单独的状况RewriteCond指令)如果您只想针对单个 URL 做出例外处理。

测试前您需要清除浏览器缓存,因为 301(永久)重定向将被浏览器缓存(可能还有中间缓存)。使用 302(临时)重定向进行测试可避免潜在的缓存问题。

在旁边:将剩余的 URL 重定向到主页在新域名上重定向通常对 SEO 和用户不利。通常,最好向用户提供带有有意义信息的自定义 404。重定向到主页会使这些页面在搜索结果中停留更长时间,但最终会被搜索引擎(包括 Google)视为软 404。当用户最终进入他们不期望的页面时,他们会感到困惑并直接跳出。

或者,使用 mod_alias:

# Specific redirects:
Redirect 301 /old-page https://www.new-domain.com/new-page

# Catch the rest, except the sitemap:
RedirectMatch 301 ^/(?!sitemap\.xml).* https://www.new-domain.com/

请注意,mod_alias 没有单独的“条件”。相反,我们在捕获所有规则中使用负向预测来做出例外。

答案2

作为建议使用 mod_alias 进行简单重定向,解决方案如下mod_alias

# Specific redirects:
Redirect 301 /old-prefix https://www.example.com/
Redirect 301 /another-old-prefix/  https://www.example.com/path/

# Catch the rest, except the sitemap:
RedirectMatch 301 ^/(?!sitemap\.xml$).* https://www.example.com/

主要功能区别在于Redirect它会重定向具有相同前缀的所有内容。

然后任何以 URL-path 开头的请求都会返回一个重定向请求到目标 URL 位置的客户端。匹配到的 URL-path 之外的其他路径信息将附加到目标 URL 中。

相关内容