需求:
如何使用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( \'< type=\" \">document.location.href=\"\'.$httpsURL.\'\";</ >\' );
}
}
}
然后,在靠近要强制通过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] 继续阅读与本文标签相同的文章
-
Surprise 你天天登录的OA系统,全新升级啦
2026-05-15栏目: 教程
-
IEEE计算机协会“人工智能与智能制造工作组全会”即将召开!
2026-05-15栏目: 教程
-
5G在未来如何助力工业物联网
2026-05-15栏目: 教程
-
Uber在巴黎部署摩托车共享服务 租金一分钟29美分
2026-05-15栏目: 教程
-
当科技时代的到来银行数据仓库将如何让发展
2026-05-15栏目: 教程
