的.htaccess重定向非www和非HTTP到https:// WWW

问题描述:

我试图重定向:的.htaccess重定向非www和非HTTP到https:// WWW

  • http://example.extension
  • https://example.extension
  • http://www.example.extension

  • https://www.example.extension

使用:

RewriteCond %{HTTP_HOST} ^example.extension$ [OR] 
RewriteCond %{HTTPS_HOST} ^example.extension$ [OR] 
RewriteCond %{HTTP_HOST} ^www.example.extension$ [NC] 
RewriteRule (.*) https://www.example.extension$1 [R=301,L] 

http://example.extension被重定向到https://www.example.extension,不过,我收到错误:

The page isn’t redirecting properly

this answer,如果我改变.htaccess规则:

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

即使清除浏览器缓存后也会出现相同的症状。

另外,我有一些子域我不想重定向到www,如:

我需要http://*.example.extension重定向到https://*.example.extension

除了我正在请求帮助的重写规则外,中的唯一其他内容是WordPress相关:

# BEGIN WordPress 
RewriteEngine On 
RewriteBase/
RewriteRule ^index\.php$ - [L] 

# add a trailing slash to /wp-admin 
RewriteRule ^wp-admin$ wp-admin/ [R=301,L] 

RewriteCond %{REQUEST_FILENAME} -f [OR] 
RewriteCond %{REQUEST_FILENAME} -d 
RewriteRule^- [L] 
RewriteRule ^(wp-(content|admin|includes).*) $1 [L] 
RewriteRule ^(.*\.php)$ $1 [L] 
RewriteRule . index.php [L] 
# END WordPress 

# BEGIN MainWP 
# END MainWP 

帮助赞赏。

随着CloudFlare的,你必须使用CloudFlare的页面规则: https://support.cloudflare.com/hc/en-us/articles/200170536-How-do-I-redirect-all-visitors-to-HTTPS-SSL-

但是你可以使用:

RewriteEngine On 

#main domain 
RewriteCond %{HTTP_HOST} !^www\. [NC,OR] 
RewriteCond %{HTTP:CF-Visitor} '"scheme":"http"' 
RewriteCond %{HTTP_HOST} ^(?:www\.)?(example\.extension)$ [NC] 
RewriteRule^https://www.%1%{REQUEST_URI} [R=301,L,NE] 

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

嗨Croises。这些规则是否考虑到我拥有的子域?我已经添加了这些规则,取代了现有规则,Firefox说:“Firefox已经检测到服务器正在以一种永远不会完成的方式重定向这个地址的请求。 我已经添加了一个Cloudflare页面规则设置'http:// *。example.extension/*'来始终使用'https',我认为这很好。 – Steve

+0

我修改了您的子域问题更改的代码。 – Croises

+0

您可以使用CloudFlare规则完成所有工作,但是避免在将CloudFlare代理重定向到错误的域后 – Croises

没有变量HTTPS_HOST

这一规则替换您的规则:

RewriteEngine On 

# main domain: add www and turn on https in same rule 
RewriteCond %{HTTP_HOST} !^www\. [NC,OR] 
RewriteCond %{HTTPS} off 
RewriteCond %{HTTP_HOST} ^(?:www\.)?(example\.extension)$ [NC] 
RewriteRule^https://www.%1%{REQUEST_URI} [R=301,L,NE] 

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

确保彻底清除浏览器缓存。

+0

感谢。我用上面的代码替换了'.htaccess'规则,即使在清除浏览器和CDN(Cloud Flare)缓存后,也会出现相同的症状。 – Steve

+0

我忘了添加我有一些子域需要重定向从'http'到'https'(即我需要'http:// * example.extension'重定向到'https://*.example .extension“也)。 – Steve

+0

这个规则来自一个实时网站,它正在工作。我为子域添加单独的规则,但首先测试主域,并确保在测试时没有其他规则。 – anubhava