Friday, May 7, 2010

How to allow trailing slash in urls in Symfony (1.4)

Symfony's routing system is made so it doesn't allow trailing slashes. It's really a problem, because it can't be solved through just some rewrite rule in .htaccess, because the request path info is not coming from .htaccess (but from the $_SYSTEM array).

Of course there is an easy solution. Symfony's factory architecture makes it easy to extend or modify built-in functionality. All you have to do is to change the routing class in factories.yml and prepare that class:

/apps/frontend/config/factories.yml:
all:
routing:
# class: sfPatternRouting
class: myPatternRouting

Create the class:
apps/frontend/lib/myPatternRouting.class.php
<?php
class myPatternRouting extends sfPatternRouting
{
protected function normalizeUrl($url)
{
$url = parent::normalizeUrl($url);

// remove trailing slash
$url = preg_replace('/\/$/', '', $url);

return $url;
}
}

Okey, this is it.

But maybe it's a better way to catch the flow in an earlier point. Because this way, though routing will parse urls with trailing slashes fine, but calls to $request->getPathInfo() will still give the urls with the trailing slashes. It can has some unwanted side effects. It's better if the whole framework sees the request url as if it had no trailing slash.

What to do for that? Change the request class instead of the routing.

/apps/frontend/config/factories.yml:
all:
routing:
class: sfPatternRouting

request:
class: myWebRequest

apps/frontend/lib/myWebRequest.class.php
<?php
class myWebRequest extends sfWebRequest
{
public function getPathInfo()
{
$pathInfo = parent::getPathInfo();

// cut off trailing slash
$pathInfo = preg_replace('/\/$/', '', $pathInfo);

return $pathInfo;
}
}

4 comments:

  1. or just edit .htaccess

    #to avoid trailing slash problem
    RewriteRule ^(.+)/$ http://%{HTTP_HOST}/$1 [R=301,L]

    ReplyDelete
  2. Thanks that's fine also, though i don't really like external redirects.

    ReplyDelete
  3. But can we make it a pluggin ?

    ReplyDelete