如何使用MVC使网站指向https版本

时间:2017-12-30 20:47:20

标签: php

在使用MVC之前,我只是习惯使用此行来使网址转到https。因此,如果用户在www.example.com中输入,则会将其带到https://example.com

  RewriteRule (.*) https://example.com/$1 [R]

但是,当我尝试使用我的MVC网站时,输入www.example.com会将我带到该网址,并且不会重定向到https。我必须手动输入https://mexample.com才能转到https版本。我怎样才能解决这个问题?

在我的根目录中,我的.htaccess看起来像:

<IfModule mod_rewrite.c>
 RewriteEngine on
 RewriteRule ^$ public/ [L]
 RewriteRule (.*) public/$1 [L]
 RewriteRule (.*) https://example.com/$1 [R]
</IfModule>

然后在我的公共文件夹中,我的.htaccess看起来像:

<IfModule mod_rewrite.c>
 Options -Multiviews
 RewriteEngine On
 RewriteBase /public
 RewriteCond %{REQUEST_FILENAME} !-d
 RewriteCond %{REQUEST_FILENAME} !-f
 RewriteRule ^(.+)$ index.php?url=$1 [QSA,L]
 </IfModule>

1 个答案:

答案 0 :(得分:1)

我一般不会在.htaccess中这样做,因为我喜欢在应用程序中设置灵活性来强制或不强制,加上我使用反向代理和Cloudflare,所以这样做会迫使我在app之间设置end2end证书服务器并锁定我使用apache2而不是nginx或caddyserver。

所以我只是在基础控制器的PHP中完成它,例如:

// is https
$https = false;
if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') {
    $https = true;
}
elseif (!empty($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https' || !empty($_SERVER['HTTP_X_FORWARDED_SSL']) && $_SERVER['HTTP_X_FORWARDED_SSL'] == 'on') {
    $https = true;
}

// is not https but required as https in config
if (!$https && $this->f3->get('app.security.force_https') === true) {
    exit(header('Location: '.$this->f3->get('site.url'), 302));
}

如果您想在.htaccess中执行此操作,请执行以下操作:

# ----------------------------------------------------------------------
# | Forcing `https://`                                                 |
# ----------------------------------------------------------------------

# Redirect from the `http://` to the `https://` version of the URL.
# https://wiki.apache.org/httpd/RewriteHTTPToHTTPS

<IfModule mod_rewrite.c>
     RewriteEngine On
     RewriteCond %{HTTPS} !=on
     RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L]
</IfModule>