> Symfony中文手册 > 如何在不同的URL中强制使用HTTPS或HTTP

如何在不同的URL中强制使用HTTPS或HTTP

你可以强制自己的网站在security配置信息中使用HttpS协议。他是通过在 Access_control 规则中使用 requires_channel 选项来完成的。例如,如果你要强制所有以 /secure 开头的URLs使用HTTPS,那么你应该使用以下配置:

1
2
3
4
5
6
# app/config/security.yml
security:
    # ...

    access_control:
        - { path: ^/secure, roles: ROLE_ADMIN, requires_channel: https }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<!-- app/config/security.xml -->
<?xml version="1.0" encoding="UTF-8"?>
<srv:container xmlns="http://symfony.com/schema/dic/security"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:srv="http://symfony.com/schema/dic/services"
    xsi:schemaLocation="http://symfony.com/schema/dic/services
        http://symfony.com/schema/dic/services/services-1.0.xsd">
 
    <config>
        <!-- ... -->
 
        <rule path="^/secure" role="ROLE_ADMIN" requires_channel="https" />
    </config>
</srv:container>
1
2
3
4
5
6
7
8
9
10
11
12
// app/config/security.php
$container->loadFromExtension('security', array(
    // ...
 
    'access_control' => array(
        array(
            'path'             => '^/secure',
            'role'             => 'ROLE_ADMIN',
            'requires_channel' => 'https',
        ),
    ),
));

登录表单本身需要能够匿名访问,否则用户将无法进行身份验证。要强制其使用HTTPS,你仍然可以使用 access_control 规则中的 IS_AUTHENTICATED_ANONYM role(属性):

1
2
3
4
5
6
# app/config/security.yml
security:
    # ...

    access_control:
        - { path: ^/login, roles: IS_AUTHENTICATED_ANONYMOUSLY, requires_channel: https }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<!-- app/config/security.xml -->
<?xml version="1.0" encoding="UTF-8"?>
<srv:container xmlns="http://symfony.com/schema/dic/security"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:srv="http://symfony.com/schema/dic/services"
    xsi:schemaLocation="http://symfony.com/schema/dic/services
        http://symfony.com/schema/dic/services/services-1.0.xsd">
 
    <config>
        <!-- ... -->
 
        <rule path="^/login"
            role="IS_AUTHENTICATED_ANONYMOUSLY"
            requires_channel="https"
        />
    </config>
</srv:container>
1
2
3
4
5
6
7
8
9
10
11
12
// app/config/security.php
$container->loadFromExtension('security', array(
    // ...
 
    'access_control' => array(
        array(
            'path'             => '^/login',
            'role'             => 'IS_AUTHENTICATED_ANONYMOUSLY',
            'requires_channel' => 'https',
        ),
    ),
));

也可以在路由配置中使用HTTPS,参考 如何强制路由总是使用HTTPS或HTTP 以了解更多。