在 Yii2 上强制使用 HTTPS

2022-01-07 00:00:00 php iis yii2 yii2-advanced-app

要求

如何在 Yii2 上强制重定向到 https(如果用户访问 http 则重定向)?我已经尝试过 web.config 强制使用 https,但它没有用.

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.

场景

我使用的是在 IIS 7.5 上托管的 Yii2 高级应用.

I am using Yii2 advanced app hosted on IIS 7.5.

推荐答案

在 IIS 上非常简单.可以使用重写模块来解决这个问题.例如,

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>

它非常有效和快速.可以用于我们自己的 CDN url,无需 PHP 代码的帮助.
此代码也可用于 ASP.Net.在这种情况下,删除隐藏 Yii 索引部分.

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.

相关文章