高级 Symfony 路由 - 排除特定主机

Advanced Symfony Routing - exclude a particular host

我有两条路径相同的路线 (/about/)。我希望 example3.com 去路线 B,所有其他人 domains/hosts 去路线 A。这可能吗?

例如:

http://example.com/about/ -> route A
http://example2.com/about/ -> route A
http://example3.com/about/ -> route B
http://example4.com/about/ -> route A
http://example5.com/about/ -> route A

我将路由 B 设置为仅匹配主机字段中的 example3.com,但是,当我将路由 A 添加到混合中时,example3.com 正在使用它而不是路由 B。

我找到了答案 - 您需要为路由使用很少使用的 "condition" 配置。

/**
 * @Route("/about/", name="global_about_us", condition="not (context.getHost() matches '/example3\.com/')")
 */
public function aboutUsAction() {
    return new Response('global about us'); //todo
}

我想这就是你要找的:

http://symfony.com/doc/current/components/routing/hostname_pattern.html

已更新

您应该像这样在 routing.yml 中移动路线:

about_example3_com:
    path:     /about
    host:     example3.com
    defaults: { _controller: AcmeDemoBundle:Main:aboutEx3 }

global_example:
    path:     /about
    defaults: { _controller: AcmeDemoBundle:Main:about }

我必须准确地做到这一点,以下是我如何做到的概要:

在我的防火墙中:

    main:
            context: user
            host: ^(app|portal)\.xxxxx\.com
            pattern: ^/
            oauth:
                resource_owners:
                    facebook: "/login/check-facebook"
                success_handler: security_handler
                login_path: /
                check_path: /connect
                default_target_path: /
                failure_path: /
                oauth_user_provider:
                    service: xxxxx.oauth.user_provider
            form_login:
                provider: fos_userbundle
                success_handler: xxxx.authentication_handler
                failure_handler: xxxx.authentication_handler
            logout: true
            anonymous: true
        public:
            anonymous: ~

值得注意的是,主防火墙中的 host 条目。您会注意到我将其设置为仅适用于应用程序或门户的子域。因此 testing.whatever.com 之类的东西将不匹配此防火墙,并移动到标记为 public 的第二个防火墙,它允许匿名访问。

接下来我们必须查看我们的 routing.yml 文件,这是排除项的来源:

dynamic_homepage:
    path:   /
    host:   "{hostname}.xxxxx.com"
    defaults:
        _controller: WebBundle:Dashboard:hostLoader
    requirements:
        hostname: "^((?!app|portal).)*$"

main_homepage:
    path:   /
    host:   portal.xxxxxx.com
    defaults: { _controller: WebBundle:Dashboard:index }

这里发生了两件事。

  1. 如果主机名以应用或门户开头,它将移至下一个(主)主页。

  2. 对于任何其他子域,它将匹配并加载第一个路由。

在您的控制器操作中,您可以使用 Request 对象来获取请求的子域。

例如

// User requested testing.xxxxx.com
function hostLoaderAction(Request $request) {
    $hostname = $request->get('hostname'); // hostname was a placeholder in our route

    // $hostname now equals 'testing'
}