【问题标题】:Redirect http to https with www using .htaccess使用 .htaccess 将 http 重定向到带有 www 的 https
【发布时间】:2019-07-07 01:12:11
【问题描述】:

如何使用.htaccess 将 HTTP 重定向到包含 WWW 的 https?

例子:

  1. http://example.com 重定向到https://www.example.com
  2. http://www.example.com 重定向到https://www.example.com
  3. https://example.com 重定向到https://www.example.com

我在努力

RewriteEngine On

RewriteCond %{HTTP:CF-Visitor} '"scheme":"http"' [OR]
RewriteCond %{HTTP_HOST} ^example\.com$ [NC]
RewriteRule ^ https://www.example.com%{REQUEST_URI} [NE,R=301,L]

RewriteCond %{HTTP:CF-Visitor} '"scheme":"http"'
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [NE,R=301,L]

【问题讨论】:

  • 如果您能向我们展示您的尝试,那就太好了!
  • @M.K 帖子已更新代码
  • 请不要使用不必要的标签 - 这个问题与 JS、PHP 或 HTML 无关
  • @NicoHaase 这不是重复的。您可以将其称为类似问题,并且我使用 stackoverflow 建议我的标签。

标签: .htaccess ssl redirect https server


【解决方案1】:

APACHE

RewriteCond %{HTTPS} off 
RewriteCond %{HTTPS_HOST} !^www.example.com$ [NC]
RewriteRule ^(.*)$ https://www.example.com/$1 [L,R=301]

NGINX

server {
    listen 443 ssl;
    server_name example.com;

    ssl_certificate /srv/www/example.com/keys/ssl.crt;
    ssl_certificate_key /srv/www/example.com/keys/www.example.com.key;
    return 301 https://www.example.com$request_uri;
}

你可以替换 ssl on;带有监听 443 ssl 的指令;来自nginx documentation的推荐。

【讨论】:

    【解决方案2】:

    您可以将以下代码放入您的.htaccess 文件中

    RewriteEngine On
    # ensure www.
    RewriteCond %{HTTP_HOST} !^www\. [NC]
    RewriteRule ^ https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
    
    # ensure https
    RewriteCond %{HTTP:X-Forwarded-Proto} !https 
    RewriteCond %{HTTPS} off
    RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
    

    .htaccess 文件会将http://example.com/ 重定向到https://example.com/

    代码说明n:

    • [NC] 匹配 URL 的大小写版本
    • X-Forwarded-Proto (XFP) 标头是用于识别协议的事实上的标准标头

    【讨论】:

      【解决方案3】:

      试试这个

      RewriteEngine On
      RewriteCond %{HTTPS} !=on
      RewriteRule ^.*$ https://%{SERVER_NAME}%{REQUEST_URI} [R,L]
      

      【讨论】:

      • 请为这些规则添加一些解释 - “试试这个”并不能帮助 OP 了解您所做的更改以及为什么此更改会产生影响
      【解决方案4】:
      RewriteEngine On 
      RewriteCond %{HTTP_HOST} ^example\.com [NC]
      RewriteCond %{SERVER_PORT} 80 //If you want the condition to match port
      RewriteRule ^(.*)$ https://www.example.com/$1 [R,L]
      

      试试这个。希望这对您有所帮助。

      【讨论】:

      • 请为这些规则添加一些解释 - “试试这个”并不能帮助 OP 了解您所做的更改以及为什么此更改会产生影响
      猜你喜欢
      • 2015-02-16
      • 2016-01-20
      • 1970-01-01
      • 2016-08-31
      • 1970-01-01
      • 2017-01-12
      • 2014-03-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多