Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exclude paths in routing

I am currently using a requirements path in Symfony2 to match any URL and handle request appropriately. For example "example.com/blog/posts/my-new-post" would return the path blog/posts/my-new-post to the controller which I would then split and check for existing data etc. This works fine, the problem is that the way the routing is configured means it will always return the same template file even if I have additional routes set up.

symfony_default_page:
    path:     /{path}
    defaults: { _controller: SymfonyBundle:Default:page }
    requirements:
        path: "^.+"

However if I wanted to call "forum" or "admin" in the url it would automatically use the above routing configuration. Is there any way to exclude particular paths and let the appropriate routing / controller handle those requests?

For example:

requirements:
    path: "^ (exclude: "admin/" and "blog/") .+"

So if admin, admin/ or admin/other-areas are access, it will use their routing configuration and if they don't' exist, throw a 404.

like image 561
iswinky Avatar asked Aug 10 '14 14:08

iswinky


2 Answers

Turns out pretty basic regex will solve this problem:

^(?!admin|login|blog).+

symfony_default_page:
    path:     /{path}
    defaults: { _controller: SymfonyBundle:Default:page }
    requirements:
        path: "^(?!admin|login|blog).+"

But as @Santiago00 suggested, it's easier just to place different routes in the correct order in your bundle/config/routing.yml or if you're using multiple bundles change the order of the imported bundles in app/config/routing.yml

like image 153
iswinky Avatar answered Sep 30 '22 05:09

iswinky


Try declaring the "admin" and "blog" routes before your default route, you can read more about this in the Symfony Book http://symfony.com/doc/current/book/routing.html#adding-requirements

Earlier Routes always Win

What this all means is that the order of the routes is very important. If the blog_show route were placed above the blog route, the URL /blog/2 would match blog_show instead of blog since the {slug} parameter of blog_show has no requirements. By using proper ordering and clever requirements, you can accomplish just about anything.

like image 42
Santiag00 Avatar answered Sep 30 '22 04:09

Santiag00