使用 .htaccess 和 mod_rewrite 强制 SSL/https [英] Force SSL/https using .htaccess and mod_rewrite

查看:20
本文介绍了使用 .htaccess 和 mod_rewrite 强制 SSL/https的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用 PHP 中特定的 .htaccess 和 mod_rewrite 页面强制使用 SSL/https.

How can I force to SSL/https using .htaccess and mod_rewrite page specific in PHP.

推荐答案

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

这篇关于使用 .htaccess 和 mod_rewrite 强制 SSL/https的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆