.htaccess将非www和非http重定向到https:// www

时间:2016-09-22 06:15:30

标签: .htaccess url-rewriting

我正在尝试重定向:

  • 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,但是,我收到错误:

  

页面未正确重定向

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

除了我要求帮助的重写规则之外,.htaccess中唯一与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

帮助表示赞赏。

2 个答案:

答案 0 :(得分:2)

没有名为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]

确保完全清除浏览器缓存。

答案 1 :(得分:1)

使用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]