【问题标题】:HTACCESS 301 Redirect Rule to point all URL Variations to the Live URLHTACCESS 301 重定向规则将所有 URL 变体指向实时 URL
【发布时间】:2017-01-20 19:14:11
【问题描述】:

我正在尝试实现 99% 的工作,但有一个小问题。

假设我的实时网址是https://www.example.com/sample-page/

我希望以下所有 URL 变体重定向到具有 301 状态的实时 URL。

http://example.com/sample-page/
http://www.example.com/sample-page/
https://example.com/sample-page/

以上所有内容都应重定向到https://www.example.com/sample-page/

我设法通过使用下面显示的 htaccess 规则来完成这项工作。

RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
RewriteCond %{HTTP_HOST} !^www\.(.*)$ [NC]
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

上述规则的问题在于:http://example.com/sample-page/ 执行双重重定向。

http://eyeacademy.com/expert-eye-examination/
301 Moved Permanently
https://eyeacademy.com/expert-eye-examination/
301 Moved Permanently
https://www.eyeacademy.com/expert-eye-examination/
200 OK

如您所见,http 重定向到 https,然后 https 非 www 重定向到 https www。我一直在尝试对这条规则进行一些调整并阅读,但我相信这里有人会有更快、更强大的解决方案?

【问题讨论】:

  • 把 https 规则放在最后?
  • 试过了。它通过添加 www.www 来破坏 https 非 www 的 URL。到域。
  • 取消L最后一条规则。
  • @123 取消 L 对一切期望 http://www.eyeacademy.com/about-us/ 重定向到 https://www.eyeacademy.com/ 而不是 https://www .eyeacademy.com/about-us/

标签: apache .htaccess mod-rewrite https url-redirection


【解决方案1】:

您可以使用这条规则重定向http -> https并添加www,并且无需在规则中硬编码主机名:

RewriteCond %{HTTP_HOST} !^www\. [NC,OR]
RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
RewriteRule ^ https://www.%1%{REQUEST_URI} [L,R=301,NE]

您还可以重新排序现有规则并避免像这样的多次重定向:

# first add www and make sure it is https://
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^ https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301,NE]

# http -> https
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301,NE]

【讨论】:

  • 谢谢。第一个选项有效。我也试试第二个。
  • See this 和标题 非捕获组
【解决方案2】:

在您的 RewriteCond 指令中使用 or 标志。将所有内容替换为以下内容:

RewriteCond %{HTTPS} off [NC,OR]
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^ https://www.example.com%{REQUEST_URI} [L,R=301]

【讨论】:

  • 建议的解决方案应该是HTTP_HOST agnostic
  • @freedev 为什么? OP没有提到这样的要求。无论如何,通用重定向也不应该很难实现。
  • @hjpotter 最好不要对域名进行硬编码。例如可能有两个域指向同一个文件夹,即 Magento 多站点
猜你喜欢
  • 2021-01-06
  • 2010-12-22
  • 2011-01-05
  • 1970-01-01
  • 2015-07-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多