我如何使用.htaccess和mod_rewrite页面特定于PHP强制到SSL/https。
当前回答
尝试这段代码,它将工作于所有版本的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)
其他回答
基于mod重写的解决方案:
在htaccess中使用以下代码自动将所有http请求转发到https。
RewriteEngine on
RewriteCond %{HTTPS}::%{HTTP_HOST} ^off::(?:www\.)?(.+)$
RewriteRule ^ https://www.%1%{REQUEST_URI} [NE,L,R]
这将重定向你的非www和www http请求到https的www版本。
其他解决方案(Apache 2.4*)
RewriteEngine on
RewriteCond %{REQUEST_SCHEME}::%{HTTP_HOST} ^http::(?:www\.)?(.+)$
RewriteRule ^ https://www.%1%{REQUEST_URI} [NE,L,R]
这在低版本的apache上不起作用,因为%{REQUEST_SCHEME}变量从2.4开始被添加到mod-rewrite中。
简单易行,只需添加以下内容
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
尝试这段代码,它将工作于所有版本的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)
这个代码适用于我
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP:X-HTTPS} !1
RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L]
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]
推荐文章
- 移动一个文件到服务器上的另一个文件夹
- Laravel中使用雄辩的ORM进行批量插入
- PHP 5.4调用时引用传递-容易修复可用吗?
- 格式化字节到千字节,兆字节,千兆字节
- 如何在PHP中获得变量名作为字符串?
- 用“+”(数组联合运算符)合并两个数组如何工作?
- Laravel PHP命令未找到
- 如何修复从源代码安装PHP时未发现xml2-config的错误?
- 在PHP中对动态变量名使用大括号
- 如何从对象数组中通过对象属性找到条目?
- 如何从关联数组中删除键及其值?
- PHP字符串中的花括号
- PHP -如何最好地确定当前调用是否来自CLI或web服务器?
- 无法打开流:没有这样的文件或目录
- 在php中生成一个随机密码