为了账号安全,请及时绑定邮箱和手机立即绑定

使用.htaccess和mod_rewrite强制使用SSL/https

使用.htaccess和mod_rewrite强制使用SSL/https

PHP
GCT1015 2019-06-25 13:25:32
使用.htaccess和mod_rewrite强制使用SSL/https如何使用.htaccess和PHP中特定的mod_rewrite页面强制使用SSL/https。
查看完整描述

3 回答

?
泛舟湖上清波郎朗

TA贡献1818条经验 获得超3个赞

我找到了一个mod_rewrite对代理服务器和未代理服务器都有效的解决方案。

如果你用CloudFlare,AWS弹性负载平衡,Heroku,OpenShift或任何其他云/PaaS解决方案重定向回路对于正常的HTTPS重定向,请尝试下面的片段。

RewriteEngine On# If we receive a forwarded http request from a proxy...RewriteCond %{HTTP:X-Forwarded-Proto} =http [OR]
# ...or just a plain old http request directly from the clientRewriteCond %{HTTP:X-Forwarded-Proto} =""RewriteCond %{HTTPS} !=on
# Redirect to https versionRewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]


查看完整回答
反对 回复 2019-06-25
?
繁星点点滴滴

TA贡献1803条经验 获得超3个赞

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重写解

我没有亲自实现这种解决方案(我倾向于使用PHP解决方案,就像上面的解决方案一样,因为它的简单性),但至少下面是一个好的开始。

RewriteEngine on# Check for POST SubmissionRewriteCond %{REQUEST_METHOD} !^POST$# Forcing HTTPSRewriteCond %{HTTPS} !=on [OR]RewriteCond 
%{SERVER_PORT} 80# Pages to ApplyRewriteCond %{REQUEST_URI} ^something_secure [OR]RewriteCond %{REQUEST_URI} ^something_else_secureRewriteRule
 .* https://%{SERVER_NAME}%{REQUEST_URI} [R=301,L]# Forcing HTTPRewriteCond %{HTTPS} =on [OR]RewriteCond %{SERVER_PORT} 443
 # Pages to ApplyRewriteCond %{REQUEST_URI} ^something_public [OR]RewriteCond %{REQUEST_URI} ^something_else_publicRewriteRule .
 * http://%{SERVER_NAME}%{REQUEST_URI} [R=301,L]


查看完整回答
反对 回复 2019-06-25
  • 3 回答
  • 0 关注
  • 676 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信