'Symfony 4 : load config or route based on .env

I am working on a Symfony 4.3 app. We recently created an API on the /api routes. However we would like to enable/disable all route after /api based on an Environment variable.
All API routes are loaded using a directory which is loaded in routes.yaml

api_directory:
    resource: 'routes/API/'
    type:     directory
    prefix: /api
    name_prefix: api_

Is there any way to tell symfony not to load these file/routes depending on the .env ?
Or redirect all request to /api to a specific 404 error page/controller ?
I've read about Routes Loader but if possible I'd like not move the routing outside the usual structure and keep the standard architecture.



Solution 1:[1]

You can try using the symfony/expression-language component, chances are that you already have it installed if you require validator in your app. It allows you to place conditions in routes.yaml.

For this case, you should be looking in the $_SERVER variables, and the expression has to be true for the route to load; for intance, load the route only on the prod environment:

api_directory:
    condition: request.server.get('APP_ENV') == 'prod'

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 msg