如何强制HTTPS(Cloudflare Flexible SSL)



我在自己编程的网站上使用Cloudflare Flexible SSL(没有框架或CMS)。一切正常,现在我想在整个网站上使用 HTTPS。我在Apache网络服务器上使用PHP。

我想知道如何解决这个问题并将所有用户重定向到 HTTPS。

目前我的 .htaccess 是这样设置的:

# Force www.
RewriteCond %{HTTP_HOST} ^example.com [NC]
RewriteRule ^(.*)$ http://www.example.com/$1 [R=301,L]

我在stackoverflow上看到了这个答案,但它指向了另一个答案,它并不那么简单,不建议重写。

这是 Apache 的建议:

<VirtualHost *:80>
    ServerName www.example.com
    Redirect "/" "https://www.example.com/"
</VirtualHost >
<VirtualHost *:443>
    ServerName www.example.com
    # ... SSL configuration goes here
</VirtualHost >

但坦率地说,我不知道这意味着什么。

如何将用户重定向到 HTTPS 和 www?切换到HTTPS时,我应该注意什么?

最好的方法是使用 Cloudflare。

在Cloudflare网站上:

  1. 转到"页面规则"顶部按钮
  2. 添加新规则:始终使用 https [ON]

或者您可以在.htaccess中使用:

RewriteEngine On
# Redirect with www
RewriteCond %{HTTP_HOST} !^www.example.com [NC,OR]
# Redirect to https
#    With Cloudflare:
RewriteCond %{HTTP:CF-Visitor} '"scheme":"http"'
#    Without Cloudflare:
# RewriteCond %{HTTPS} off 
RewriteRule ^ https://www.example.com%{REQUEST_URI} [NE,R=301,L]

看起来之前的所有答案都已经过时了。

以下是对我有用的方法:

RewriteCond %{HTTPS} off
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteCond %{HTTP:CF-Visitor} !https
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

我通过转到支持文章如何在使用 WordPress 启用灵活 SSL 后修复无限重定向循环错误来想出这个?。然后我去了链接的CloudFlare Flexible SSL。我查看了源代码,发现:

public function run() {
  $aIcwpHttpsServerOpts = array( 'HTTP_CF_VISITOR', 'HTTP_X_FORWARDED_PROTO' );
  foreach( $aIcwpHttpsServerOpts as $sOption ) {
    if ( isset( $_SERVER[ $sOption ] ) && ( strpos( $_SERVER[ $sOption ], 'https' ) !== false ) ) {
      $_SERVER[ 'HTTPS' ] = 'on';
      break;
    }
  }
  if ( is_admin() ) {
    add_action( 'admin_init', array( $this, 'maintainPluginLoadPosition') );
  }
}

然后我把它翻译成一条.htaccess规则。

嗯,

我认为有一个简单的方法
只需打开云耀斑 dashbaoard
转到加密部分
在 SSL 部分中,选择"完全"向下滚动,您将看到此部分

始终使用 HTTPS将所有具有方案"HTTP"的请求重定向到"HTTPS"。这适用于对区域的所有 HTTP 请求。
将其打开
全部完成

这样的事情可能会起作用:

   RewriteEngine On
   RewriteCond %{HTTPS} off
   RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}

您可以尝试将其放入.htaccess文件中。

RewriteEngine On
RewriteCond %{HTTP:CF-Visitor} '"scheme":"http"'
RewriteRule ^(.*)$ https://www.example.com$1 [L]    

这将检查访问者是否正在访问http。如果是这样,它将重定向到同一页面的https版本。

最新更新