简体   繁体   中英

Set host globally for routes

AFAIK Symfony2 is indifferent of the host in routing unless a host is specified.

I currently don't make use of subdomains in my app, but this is going to change. What I want, is that when a subdomain is present in the host ( http://subdomain.foo.bar ), the router only matches routes if the route configuration has a subdomain in the host.

This should match: (which it does)

/**
 * @Route("/", host="{subdomain}.%host%")
 * @Template
 */
public function index()

This should not match and return 404:

/**
 * @Route("/")
 * @Template
 */
public function index()

Because of the aforementioned indifference, this route is also matched for http://subdomain.foo.bar

So what I want is to set the host requirement globally (foo.bar) and then specify for specific routes that they should also match when a subdomain is present.

I tried adding the host requirement to the import in app/config/routing.yml :

foo:
    resource: "@AcmeFooBundle/Controller/"
    type:     annotation
    host:     foo.bar
    prefix:   /

However, that host requirement "wins" from the ones specified in the annotation, resulting in no match for any of the two routes (mentioned above) when a subdomain is present in the actual host.

What does work is setting the host name globablly per controller:

/**
 * @Route(host="foo.bar")
 */
class bazController

But I'd much rather configure this somewhere globally.

Does anyone know how to solve this?

I fixed this by creating a custom route compiler:

use Symfony\Component\Routing\RouteCompiler as BaseRouteCompiler;
use Symfony\Component\Routing\Route;

class RouteCompiler extends BaseRouteCompiler
{
    public static function compile(Route $route)
    {
        if ($route->getHost() === "") {
            $route->setHost($route->getDefaults()['default_host']);
        }

        return parent::compile($route);
    }
}

Then in your routing file:

foo:
    resource: "@BarBundle/Controller/"
    type:     annotation
    prefix:   /
    options:
        compiler_class: Foo\Bundle\CoreBundle\Router\RouteCompiler
    defaults:
        default_host: %router.request_context.host%

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM