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.
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.
Its actually very easy in Yii2 as there is a predefined method for your check. Just three steps needed:
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);
}
}
}
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.
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.