首页 > 解决方案 > 使用 .htaccess 将 http 重定向到带有 www 的 https

问题描述

如何将 HTTP 重定向到 https 包括 WWW 使用.htaccess

例子 :

  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]

标签: .htaccesssslredirecthttpsserver

解决方案


您可以将以下代码放入您的.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/

代码说明

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

推荐阅读