Force HTTPS on Yii2

这一生的挚爱 提交于 2019-12-04 17:22:13

Its actually very easy in Yii2 as there is a predefined method for your check. Just three steps needed:

1. Extend the application class

Extend the default yii web-application class and override the handleRequest-method. Use the existing Yii2-function to check if the connection is secure.

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

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.

3. Done!

That's it actually... :)! Hope it helps!

It's very simple on IIS. Can use rewrite module to solve this issue. E.g.,

<?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.
This code can used for ASP.Net also. In such case, remove Hide Yii Index section.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!