phpregexsymfonyroutes

Symfony Routing Host Regular Expression


I have a route in my Symfony project that should be restricted only to hosts that contains a specific word in a subdomain, a domain is not important and it will vary. Lets say this specific word is 'pre', so I want only hosts build like this (pre.anything.com, pre.anything2.co.uk, pre.anything3.us) to access certain route. Is it possible to configure it as such in a symfony routing?

routes.yaml

base_register:
    path:     /register/
    host:     "/pre/"
    defaults: { _controller: App\Controller\AppController::registerAction }

Using:


Solution

  • Your use case is similar to the docs for subdomains : https://symfony.com/doc/4.1/routing/hostname_pattern.html#using-placeholders

    You can use this config:

    base_register:
        path:     /register/
        host:     "pre.{domain}"
        controller: App\Controller\AppController::register
        defaults:
            domain: '%domain%'
        requirements:
            domain: '%domain%'
    

    and then in your parameters.yml you define your domain param where you set your default domain.

    In your domain requirement you can set (.*) to catch both domain and subdomain.