我如何使用.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_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 client
RewriteCond %{HTTP:X-Forwarded-Proto} =""
RewriteCond %{HTTPS} !=on
# Redirect to https version
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]
简单一点:
RewriteEngine on
RewriteCond %{HTTP_HOST} ^(www\.example\.com)(:80)? [NC]
RewriteRule ^(.*) https://example.com/$1 [R=301,L]
order deny,allow
用example.com替换你的url
推荐文章
- 阻止人们入侵基于php的Flash游戏高分表的最佳方法是什么
- 如何允许本地主机上的Apache使用HTTPS ?
- PHP子字符串提取。获取第一个'/'之前的字符串或整个字符串
- __construct函数的作用是什么?
- PHP中的异步shell执行器
- Laravel 5 -如何访问在视图存储上传的图像?
- 为什么在PHP中使用sprintf函数?
- “质量分配”在Laravel中是什么意思?
- 在逗号上爆炸字符串,并修剪每个值的潜在空格
- 如何让Chrome允许混合内容?
- 无法识别的SSL消息,明文连接?异常
- PHP与MySQL 8.0+错误:服务器请求身份验证方法未知的客户端
- laravel5“LIKE”对等物(雄辩的)
- 在函数中使用默认实参
- 转换php数组到Javascript