-->

Force HTTPS on Yii2

2019-04-15 13:28发布

问题:

Requirement

How to forcibly redirect to https (redirect if user accessing http) on Yii2? I already tried web.config to force https, but it didn't work.

scenario

I am using Yii2 advanced app hosted on IIS 7.5.

回答1:

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!



回答2:

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.