我如何使用.htaccess和mod_rewrite页面特定于PHP强制到SSL/https。


当前回答

简单易行,只需添加以下内容

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

其他回答

简单易行,只需添加以下内容

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

简单一点:

RewriteEngine on
RewriteCond %{HTTP_HOST} ^(www\.example\.com)(:80)? [NC]
RewriteRule ^(.*) https://example.com/$1 [R=301,L]
order deny,allow

用example.com替换你的url

我只是想指出,当跨目录深度使用多个.htaccess文件时,Apache的继承规则是最差的。两个主要陷阱:

默认情况下,只有包含在最深的.htaccess文件中的规则将被执行。你必须指定RewriteOptions InheritDownBefore指令(或类似指令)来改变这个。(见问题) 该模式应用于相对于子目录的文件路径,而不是包含给定规则的.htaccess文件的上层目录。(见讨论)

这意味着如果您在子目录中使用任何其他.htaccess文件,则Apache Wiki上建议的全局解决方案将不起作用。我写了一个修改后的版本:

RewriteEngine On
# This will enable the Rewrite capabilities

RewriteOptions InheritDownBefore
# This prevents the rule from being overrided by .htaccess files in subdirectories.

RewriteCond %{HTTPS} !=on
# This checks to make sure the connection is not already HTTPS

RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [QSA,R,L]
# This rule will redirect users from their original location, to the same location but using HTTPS.
# i.e.  http://www.example.com/foo/ to https://www.example.com/foo/

尝试这段代码,它将工作于所有版本的url像

website.com www.website.com http://website.com http://www.website.com 重写%{HTTPS} off ^www.website.com$ [NC] RewriteRule ^ (. *) https://www.website.com/ 1美元(L, R = 301)

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强制连接的这些页面的顶部,您可以要求()一个包含此(和任何其他)自定义函数的集中文件,然后简单地运行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]