.htaccess - 如何强制 .com 域重定向到 .tld

标签 .htaccess redirect

我有两个域,比如说 example.comexample.tld。但我希望用户始终访问 .tld 域。我想使用 .htaccess 并尝试过

RewriteEngine on
RewriteRule ^(.*)$ http://example.tld/$1 [R=301,L,QSA]

当我打开 example.com 时,它会重定向到 example.tld。但是当我打开 example.tld 时出现错误

This webpage has a redirect loop

我必须如何修改重定向语句?

最佳答案

因此,您将需要一个 RewriteCond 来确保后续的 RewriteRule 仅在请求的 HTTP_HOSTexample.com 时应用

RewriteEngine On
# Apply the rule if the host does not already match example.tld
RewriteCond %{HTTP_HOST} !^example\.tld$
RewriteRule (.*) http://example.tld/$1 [L,R=301,QSA]

请注意,在使用 [R] 时,[QSA] 已经是隐式的。您实际上不需要在此处添加它,但也没有坏处。

上面的代码会将任何example.tld重定向到example.tld。如果您添加了您不想重定向的第三个域(仅重定向 example.com),而不是 RewriteCond 中的否定匹配,您可以使用肯定匹配仅限该域。

RewriteCond %{HTTP_HOST} ^example\.com$
RewriteRule (.*) http://example.tld/$1 [L,R=301,QSA]

关于.htaccess - 如何强制 .com 域重定向到 .tld,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24045056/

相关文章:

php - 为 imagejpeg/imagepng 函数创建的图像指定缓存验证器

apache - Html 页面的 URL 重写

.htaccess - htaccess 两个参数 mod-rewrite 问题

redirect - 重定向不完整网址的 Angular 方式是什么?

.htaccess - 如何防止 htaccess 重定向非 www 网址(以某些字符串开头的网址除外)?

.htaccess - 通过 htaccess 和分页获得值(value)

linux - 在 1and1 上安装 Concrete 5 后,htaccess 列出目录文件不再起作用

php - Magento 301 的 PHP 代码获取 Seo Url?

vba - 将命令行过程的输出定向到 Excel

javascript - 检测 Safari 并重定向