ris*_*2m8 2 yii2 yii2-advanced-app
需求
如何在Yii2上强制重定向到https(如果用户访问http,则重定向)?我已经尝试过web.config强制https,但它没有用.
脚本
我正在使用IIS 7.5上托管的Yii2高级应用程序.
它实际上非常容易在Yii2,因为有一个预定义的方法来检查.只需要三个步骤:
扩展默认的yii web-application类并覆盖handleRequest-method.使用现有的Yii2功能检查连接是否安全.
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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
在index.php您的文件web夹中,只需使用新的应用程序类,而不是创建应用程序实例的常规应用程序类.
那就是它...... :)!希望能帮助到你!