大网数据广告活动
网站运营与故障问答

.htaccess doesn't redirect my pages from HTTP to HTTPS

· 52CE 我爱测

It seems like .htaccess doesn't redirect my pages from http to https. My domain is redirected to https but not my pages… Can it be a bad configuration from my web host? Here is what I have done until now: Choose a SSL certificate…

问题原文

原帖链接 · Sandra · CC BY-SA 3.0

It seems like .htaccess doesn't redirect my pages from http to https. My domain is redirected to https but not my pages… Can it be a bad configuration from my web host?

Here is what I have done until now:

  • Choose a SSL certificate and installed it on my website from the host.
  • Force wp-config to pass from HTTP to HTTPs with: define('FORCE_SSL_ADMIN', true);
  • Tranform all of my URLs to HTTPs with Replace and Search DB
  • Add this domain to Google Search Console…

Put this code in my .htaccess:

<IfModule mod_rewrite.c>
RewriteEngine On
# Redirect to HTTPS 
RewriteCond %{HTTP_HOST} ^http://example\.com [NC]
RewriteCond %{SERVER_PORT} ^80$ [OR]
RewriteCond %{HTTPS} =off [OR]
RewriteRule ^(.*)$ https://example.com/$1 [L,R=301]
# Redirect from www HTTPS to HTTPS
RewriteCond %{HTTP_HOST} ^www\.example\.com [NC]
RewriteRule ^(.*)$ https://example.com/$1 [L,R=301]

RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

I think that's all… Would you have an idea of what can cause this problem?

已采纳解答

原帖链接 · MrWhite · CC BY-SA 3.0

RewriteCond %{HTTP_HOST} ^http://example\.com [NC]

The HTTP_HOST variable contains just the hostname, not the scheme + hostname, so this will never match. If this never matches then it will never redirect http://example.com/... to HTTPS. (However, you have used this correctly in your second rule block which will redirect http://www.example.com/... to HTTPS.)

I assume you only have one domain? In which case, that directive should simply be removed (not corrected).

RewriteCond %{HTTPS} =off [OR]

However, you also have an erroneous OR flag on the last RewriteCond directive. If the preceding condition(s) matched then this would result in a redirect loop, since it's essentially <condition> OR true, which is always true.

Summary

# Redirect to HTTPS 
RewriteCond %{HTTP_HOST} ^http://example\.com [NC]
RewriteCond %{SERVER_PORT} ^80$ [OR]
RewriteCond %{HTTPS} =off [OR]
RewriteRule ^(.*)$ https://example.com/$1 [L,R=301]

So, in summary, you should replace the first rule block (above) with the following:

# Redirect to HTTPS
RewriteCond %{HTTPS} =off
RewriteRule ^(.*)$ https://example.com/$1 [L,R=301]

There's no point checking both SERVER_PORT and HTTPS. Either should be sufficient; not both.

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Webmasters Stack Exchange
适用范围
以原帖系统、软件版本与发布日期为准(2017-07-07)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 3.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。