强制 silex 框架生成 https 链接

forcing silex framework to generate https links

我的整个应用程序应该通过 HTTPS 访问, 虚拟主机已正确配置,当我使用 HTTPS 前缀调用我的任何应用程序页面时,它都能正确响应。

但是,当我尝试通过我的应用程序中生成的 link 访问页面时。它总是指向常规 HTTP link.

我首先尝试使用 .htaccess 文件将所有流量重定向到 HTTPS。花了几个小时尝试我在网上找到的每一种重定向方法,但由于某种原因,我总是以无限重定向循环结束。

现在我正在尝试以不同的方式解决这个问题:在 HTTPS 中直接生成我的 links。我所有的 link 都是使用 twig-bridge 提供的 URL() 函数生成的。

使用Symfony

配置非常简单

但我不知道如何用 Silex 来做。有没有一种简单的方法可以更改 Silex 中的路由方案以强制每个 link 生成一个 HTTPS 前缀?

requireHttps() 添加到您的路线生成器,就可以了。

示例:

$app->get('/hello-world', function($app) {
    return 'Hello world';
})
->bind('hello') // Set route name (optional of course)
->requireHttps(); // This would force your url with https://

您也可以查看 API 以获取更多信息。你会在那里找到你需要的一切。

对于那个特定的案例,我解决了声明基数 url 的问题,就像 app.php:

中那样
$app['customBaseUrl'] = 'https://mybaseurl';

然后用这个自定义的 baseUrl 作为我所有链接的前缀。这些链接不再由 url() twig 函数生成。

虽然这不是最漂亮的方法。如果您的服务器配置允许您使用它,我会推荐 Artamiel 的答案。

将环境变量 HTTPS 设置为 on

Nginx 配置内部位置:fastcgi_param HTTPS on;
Apache 的 .htaccess 或虚拟主机配置:SetEnv HTTPS on

请注意,官方文档中的默认 nginx 配置将此变量设置为 off,这可能会被复制粘贴到 https 站点,但这是错误的:
http://silex.sensiolabs.org/doc/web_servers.html
Ctrl+F - fastcgi_param HTTPS off;

另一种选择是在 SecurityServiceProvider 设置中使用 access_control(如果您正在使用它)来指定某些路由需要使用 https,方法是指定 'requires_channel' => 'https' 在安全配置的 access_control 部分。

如果您使用 Controller class 中的 Controller Providers, you can use the requireHttps() 方法要求对整个路由范围使用 HTTPS:

namespace Acme;

use Silex\Application;
use Silex\Api\ControllerProviderInterface;

class HelloControllerProvider implements ControllerProviderInterface
{
    public function connect(Application $app)
    {
        $controllers = $app['controllers_factory'];
        $controllers->get('/', function (Application $app) {
            return $app->redirect('/hello');
        });
        $controllers->get('/another-page', 'Acme\HelloControllerProvider::doSomething')->bind('another-page');
        // here it goes
        $controllers->requireHttps();
        // or even make it more flexible with a config variable
        // if ($app['config']['require_https']) (
        //     $controllers->requireHttps();
        // }
        return $controllers;
    }
}