强制禁止WWW和HTTPS

时间:2016-09-21 15:58:21

标签: .htaccess mod-rewrite https url-rewriting

我有一个奇怪的问题。我的重写规则看起来像我期望的那样工作,但不适用于子页面。

www to none www始终有效,但强制https在某些页面上不起作用。

然而,所有规则在主页上都有效,所以这一切都很好。

<IfModule mod_rewrite.c>
# Wordpress related rewrite.
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]

# www and https rules.
RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ http://%1/$1 [R=301,L]

RewriteCond %{HTTPS} on
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ https://%1/$1 [R=301,L]
</IfModule>

结果:

  1. http://example.com - &gt; https://example.com(好)
  2. http://www.example.com - &gt; https://example.com(好)
  3. https://example.com - &gt; https://example.com(好)
  4. https://www.example.com - &gt; https://example.com(好)
  5. 但是,子页面似乎无法正常工作:

    1. https://example.com/page - &gt; https://example.com/page(好)
    2. https://www.example.com/page - &gt; https://example.com/page(好)
    3. http://example.com/page - &gt; http://example.com/page(不好)
    4. http://www.example.com/page - &gt; http://example.com/page(不好)
    5. 我知道如何改进这种重写,无论我的位置如何都不使用www和https吗?

      由于

2 个答案:

答案 0 :(得分:2)

用以下内容替换您的规则:

RewriteEngine On
RewriteBase /

# remove www and turn on https in single rule
RewriteCond %{HTTP_HOST} ^www\. [NC,OR]
RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
RewriteRule ^ https://%1%{REQUEST_URI} [R=301,L,NE]

RewriteRule ^index\.php$ - [L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . index.php [L]

订购非常重要,因此您必须在WP默认规则之前保留重定向规则。此外,请确保在测试此更改时清除浏览器缓存。

答案 1 :(得分:1)

www and https rules.块中,您重定向到HTTP:

RewriteRule ^(.*)$ http://%1/$1 [R=301,L]

由于您希望始终重定向到HTTPS,因此也可以将其重定向到HTTPS:

RewriteRule ^(.*)$ https://%1/$1 [R=301,L]