我如何使用.htaccess和mod_rewrite页面特定于PHP强制到SSL/https。
当前回答
简单一点:
RewriteEngine on
RewriteCond %{HTTP_HOST} ^(www\.example\.com)(:80)? [NC]
RewriteRule ^(.*) https://example.com/$1 [R=301,L]
order deny,allow
用example.com替换你的url
其他回答
基于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中。
对于Apache,你可以使用mod_ssl强制SSL与SSLRequireSSL指令:
该指令禁止访问,除非当前连接启用了HTTP over SSL(即HTTPS)。这在启用ssl的虚拟主机或目录中非常方便,可以防止暴露应该保护的内容的配置错误。当这个指令出现时,所有不使用SSL的请求都将被拒绝。
这将不会重定向到https。要重定向,请在.htaccess文件中尝试以下mod_rewrite
RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
或文中给出的任何一种方法
http://www.askapache.com/htaccess/http-https-rewriterule-redirect.html
你也可以从PHP内部解决这个问题,如果你的提供者已经禁用了.htaccess(这是不太可能的,因为你要求它,但无论如何)
if (!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] !== 'on') {
if(!headers_sent()) {
header("Status: 301 Moved Permanently");
header(sprintf(
'Location: https://%s%s',
$_SERVER['HTTP_HOST'],
$_SERVER['REQUEST_URI']
));
exit();
}
}
我只是想指出,当跨目录深度使用多个.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/
这个代码适用于我
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP:X-HTTPS} !1
RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L]
简单易行,只需添加以下内容
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
推荐文章
- 在文本文件中创建或写入/追加
- 为什么PHP的json_encode函数转换UTF-8字符串为十六进制实体?
- CFNetwork SSLHandshake iOS 9失败
- 如何从一个查询插入多行使用雄辩/流利
- 在PHP单元测试执行期间,如何在CLI中输出?
- 在PHP中使用heredoc的优势是什么?
- PHP中的echo, print和print_r有什么区别?
- 如何将XML转换成PHP数组?
- 如何将对象转换为数组?
- 从IP地址获取位置
- 获取数组值的键名
- HTTPS和SSL3_GET_SERVER_CERTIFICATE:证书验证失败,CA is OK
- PHP -获取bool值,当为false时返回false
- 在foreach中通过引用传递
- c#忽略证书错误?