【问题标题】:Using htaccess to redirect http://www, http:// and https://www to https:使用 htaccess 将 http://www、http:// 和 https://www 重定向到 https:
【发布时间】:2015-02-16 04:17:33
【问题描述】:

在我的网站上,我在非 www 版本的域上安装了 SSL 证书。我想使用 htaccess 将 http www、http 非 www 和 https www 重定向到 https://

我有 www 到非 www 工作,但 https www 不重定向到 https 非 www。这是我的 htaccess 中的内容:

Options +FollowSymLinks
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ link [R=301,L]

RewriteEngine On
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https link [R,L]

谁能帮我弄清楚我错过了什么?

莎朗

【问题讨论】:

  • 由于某种原因它不允许我发布实际链接,所以我将它们替换为“链接”。谢谢!
  • 现在我需要做相反的事情。将 http www、http 非 www 和 https 非 www 重定向到 www。我该如何改变呢?有没有我可以参考的答案?感谢您的帮助!
  • 是 - 一条将 http www、http 非 www 和 https 非 www 重定向到 https www 的规则。

标签: php apache .htaccess mod-rewrite redirect


【解决方案1】:

您可以使用:对于 http 或 https,带或不带 www -> https 不带 www

Options +FollowSymLinks
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
RewriteRule ^ https://%1%{REQUEST_URI} [R=301,L]

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

相反:对于 http 或 https,有或没有 www -> https 有 www

Options +FollowSymLinks
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^ https://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

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

【讨论】:

  • 事实证明,现在我需要相反。将 http www、http 非 www 和 https 非 www 重定向到 www。我该如何改变呢?感谢您的帮助!
  • 这个 https://%{HTTP_HOST}%{REQUEST_URI} 是否应该替换为实际域所以domain.com
  • 不,它是自动的,您无需更改任何内容
【解决方案2】:

根据您的 cmets,这里有一个规则可以在单个规则中执行以下重定向:

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

这样做:

http://www.domain.com/foobar  => https://www.domain.com/foobar
http://domain.com/foobar      => https://www.domain.com/foobar
https://domain.com/foobar     => https://www.domain.com/foobar
https://www.domain.com/foobar => Unchanged

【讨论】:

  • %1% 是干什么用的?
  • 这是 RewriteCond 中捕获组的反向引用
  • 迄今为止我遇到的最佳解决方案,因为它不需要对域名进行硬编码。谢谢
猜你喜欢
  • 2016-01-20
  • 2016-08-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-08
  • 2014-05-08
  • 2018-09-26
相关资源
最近更新 更多