使用.htaccess和mod_rewrite强制SSL / https

时间:2017-07-27
本文章向大家介绍使用.htaccess和mod_rewrite强制SSL / https,需要的朋友可以参考一下。

需求:

如何使用PHP中特定的.htaccess和mod_rewrite页面强制使用SSL / https。

PHP解决方案

直接借用Gordon非常全面的答案,我注意到你的问题提到强制HTTPS / SSL连接是特定于页面的。

function forceHTTPS(){
  $httpsURL = 'https://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
  if( count( $_POST )>0 )
    die( 'Page should be accessed with HTTPS, but a POST Submission has been sent here. Adjust the form to point to '.$httpsURL );
  if( !isset( $_SERVER['HTTPS'] ) || $_SERVER['HTTPS']!=='on' ){
    if( !headers_sent() ){
      header( "Status: 301 Moved Permanently" );
      header( "Location: $httpsURL" );
      exit();
    }else{
      die( '<script type="javascript">document.location.href="'.$httpsURL.'";</script>' );
    }
  }
}

然后,在靠近要强制通过PHP连接的这些页面的顶部,您可以require()使用包含此(和任何其他)自定义函数的集中文件,然后只需运行该forceHTTPS()函数。

HTACCESS / mod_rewrite解决方案

我没有亲自实现这种解决方案(我倾向于使用PHP解决方案,如上所述,因为它简单),但以下可能至少是一个良好的开端。

RewriteEngine on

# Check for POST Submission
RewriteCond %{REQUEST_METHOD} !^POST$

# Forcing HTTPS
RewriteCond %{HTTPS} !=on [OR]
RewriteCond %{SERVER_PORT} 80
# Pages to Apply
RewriteCond %{REQUEST_URI} ^something_secure [OR]
RewriteCond %{REQUEST_URI} ^something_else_secure
RewriteRule .* https://%{SERVER_NAME}%{REQUEST_URI} [R=301,L]

# Forcing HTTP
RewriteCond %{HTTPS} =on [OR]
RewriteCond %{SERVER_PORT} 443
# Pages to Apply
RewriteCond %{REQUEST_URI} ^something_public [OR]
RewriteCond %{REQUEST_URI} ^something_else_public
RewriteRule .* http://%{SERVER_NAME}%{REQUEST_URI} [R=301,L]