简体   繁体   English

在 Yii2 上强制使用 HTTPS

[英]Force HTTPS on Yii2

Requirement要求

How to forcibly redirect to https (redirect if user accessing http) on Yii2?如何在Yii2上强行重定向到https (如果用户访问http则重定向)? I already tried web.config to force https, but it didn't work.我已经尝试过 web.config 来强制使用 https,但是没有用。

scenario设想

I am using Yii2 advanced app hosted on IIS 7.5.我正在使用托管在 IIS 7.5 上的 Yii2 高级应用程序。

Its actually very easy in Yii2 as there is a predefined method for your check.在 Yii2 中它实际上很容易,因为有一个预定义的方法供您检查。 Just three steps needed:只需要三个步骤:

1. Extend the application class 1.扩展应用类

Extend the default yii web-application class and override the handleRequest -method.扩展默认的 yii web-application 类并覆盖handleRequest方法。 Use the existing Yii2-function to check if the connection is secure.使用现有的 Yii2-function 检查连接是否安全。

class MyApplication extends \yii\web\Application
{
    public function handleRequest($request)
    {
        //check if connection is secure
        if (!$request->isSecureConnection) {
            //otherwise redirect to same url with https
            $secureUrl= str_replace('http', 'https', $request->absoluteUrl);
            //use 301 for a permanent redirect
            return Yii::$app->getResponse()->redirect($secureUrl, 301);
        } else {
            //if secure connection call parent implementation
            return parent::handleRequest($request);
        }
    }
}

2. Use new class in index.php 2. 在 index.php 中使用新类

Within the index.php of your web -folder simply use your new application-class instead of the regular one where the application-instance is created.在您的web夹的index.php ,只需使用您的新应用程序类,而不是创建应用程序实例的常规类。

3. Done! 3. 完成!

That's it actually... :)!实际上就是这样... :)! Hope it helps!希望能帮助到你!

Just add your rule in on beforeAction event on config.php .只需在config.php on beforeAction事件中添加您的规则。

'on beforeAction' => function ($event) {
    if (!(
          (!empty($_SERVER['HTTPS']) AND $_SERVER['HTTPS'] != 'off') || 
          $_SERVER['SERVER_PORT'] == 443
        )) {
            return Yii::$app->controller->redirect("https://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]");
    }
}

This code check if user request is not http then move it to https .此代码检查用户请求是否不是http然后将其移动到https

From the PHP.net documentation :来自PHP.net 文档

for $_SERVER['HTTPS']对于$_SERVER['HTTPS']

Set to a non-empty value if the script was queried through the HTTPS protocol.如果通过 HTTPS 协议查询脚本,则设置为非空值。

Note: Note that when using ISAPI with IIS, the value will be off if the request was not made through the HTTPS protocol.注意:请注意,将 ISAPI 与 IIS 一起使用时,如果请求不是通过 HTTPS 协议发出的,则该值将关闭。

so this code should works for IIS.所以这段代码应该适用于 IIS。

for $_SERVER['SERVER_PORT'] :对于$_SERVER['SERVER_PORT']

Note: Under the Apache 2, you must set UseCanonicalName = On, as well as UseCanonicalPhysicalPort = On in order to get the physical (real) port, otherwise, this value can be spoofed and it may or may not return the physical port value.注意:在Apache 2下,必须设置UseCanonicalName = On,以及UseCanonicalPhysicalPort = On才能获取物理(真实)端口,否则这个值可能被欺骗,可能返回也可能不返回物理端口值。 It is not safe to rely on this value in security-dependent contexts.在依赖于安全的上下文中依赖此值是不安全的。

so if you have any problem in this code, you can prevent to using $_SERVER['SERVER_PORT'] in rule.所以如果你在这段代码中有任何问题,你可以阻止在规则中使用$_SERVER['SERVER_PORT']

At the end, If you want to do in whole advanced Yii2 do this config in common directory.最后,如果您想在整个advanced Yii2执行此配置,请在common目录中执行此配置。

It's very simple on IIS.这在 IIS 上非常简单。 Can use rewrite module to solve this issue.可以使用重写模块来解决这个问题。 Eg,例如,

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.webServer>

    <!-- Other stuffs -->

        <rewrite>
            <rules>
                <clear />
                <rule name="Redirect to https" stopProcessing="true">
                    <match url="(.*)" />
                    <conditions>
                        <add input="{HTTPS}" pattern="off" ignoreCase="true" />
                    </conditions>
                    <action type="Redirect" url="https://{HTTP_HOST}{REQUEST_URI}" redirectType="Permanent" appendQueryString="false" />
                </rule>

                <rule name="Hide Yii Index" stopProcessing="true">
                    <match url="." ignoreCase="false" />
                    <conditions>
                        <add input="{REQUEST_FILENAME}" matchType="IsFile" ignoreCase="false" negate="true" />
                        <add input="{REQUEST_FILENAME}" matchType="IsDirectory" ignoreCase="false" negate="true" />
                    </conditions>
                    <action type="Rewrite" url="index.php" appendQueryString="true" />        
                </rule>


            </rules>
        </rewrite>

    <!-- Other stuffs -->
    </system.webServer>    
</configuration>

It's very effective and fast.它非常有效和快速。 Can used for CDN url of our own without help of PHP code.可用于我们自己的 CDN url,无需 PHP 代码的帮助。
This code can used for ASP.Net also.此代码也可用于 ASP.Net。 In such case, remove Hide Yii Index section.在这种情况下,删除隐藏 Yii 索引部分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM