且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用 .htaccess 和 mod_rewrite 强制 SSL/https

更新时间:2023-09-12 08:06:52

对于 Apache,您可以使用 mod_ssl 使用 SSLRequireSSL 指令:

For Apache, you can use mod_ssl to force SSL with the SSLRequireSSL Directive:

该指令禁止访问,除非为当前连接启用了基于 SSL 的 HTTP(即 HTTPS).这在启用 SSL 的虚拟主机或目录中非常方便,可防止配置错误暴露应受保护的内容.当此指令存在时,所有不使用 SSL 的请求都会被拒绝.

This directive forbids access unless HTTP over SSL (i.e. HTTPS) is enabled for the current connection. This is very handy inside the SSL-enabled virtual host or directories for defending against configuration errors that expose stuff that should be protected. When this directive is present all requests are denied which are not using SSL.

虽然这不会重定向到 https.要重定向,请使用 mod_rewrite 尝试以下操作在您的 .htaccess 文件中

This will not do a redirect to https though. To redirect, try the following with mod_rewrite in your .htaccess file

RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

如果您的提供者禁用了 .htaccess,您也可以在 PHP 中解决这个问题(这不太可能,因为您要求它,但无论如何)

You can also solve this from within PHP in case your provider has disabled .htaccess (which is unlikely since you asked for it, but anyway)

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();
    }
}