On Rails 3, I'm trying to redirect from a URL without a trailing slash to the canonical URL that has a slash.
match "/test", :to => redirect("/test/")
However, the route above matches both /test and /test/ causing a redirect loop.
How do I make it match only the version without the slash?
Maybe it works with
There is an option in ActionDispatch called
trailing_slash
you can use to force the trailing slash at the end of the URL. I'm not sure if it can be used in the routing definition.In your case, the best way is to use Rack or your web server to execute the redirect. In Apache, you can add a definition such as
To redirect all routes without a trailing slash to the corresponding one with trailing slash.
Or you can use rack-rewrite to perform the same task in your Rails app at Rack level.
You can force the redirect at the controller level.
I wanted to do the same to have a cannonical url for a blog, this works
then I have another rule which deals with the relative paths inside the post. Order is important, so former goes first and generic one goes second.