3

I want to have SEO optimized urls like this

http://example.com/sites/1-blau.de/plans

But the dot in the path cause Rails to chock. How do I escape dots to percentage notation form so it can work?

My routes:

resources :sites, only: [] do
  resources :plans, only: [:index, :show] do
  end
end

I have tried URI.escape and CGI.escape, neither worked.

URI.escape('a.b')=> "a.b"
CGI.escape('a.b')=> "a.b"

What I thought I wanted

Foo.escape('a.b')=> "a%2Eb"
5
  • Have you tried `backslash \`?
    – Bala
    Commented May 15, 2014 at 8:22
  • @Bala what do you mean?
    – lulalala
    Commented May 15, 2014 at 8:23
  • I think he means \.
    – mdesantis
    Commented May 15, 2014 at 8:24
  • 1
    Foe me URI.escape is working fine.enc_uri = URI.escape("http://example.com/sites/1-blau.de/plans") => "http://example.com/sites/1-blau.de/plans"
    – Pavan
    Commented May 15, 2014 at 8:31
  • I realized even if I escape it by hand (convert period mark to "%2E") it wouldn't work, because browser will convert it automatically back to period.
    – lulalala
    Commented May 15, 2014 at 8:39

2 Answers 2

7

Use a constraint that accepts dot character.

get 'sites/:site_name/plans', constraints: { site_name: /[a-zA-Z0-9\.]+/ }

From the doc:

By default, dynamic segments don't accept dots - this is because the dot is used as a separator for formatted routes. If you need to use a dot within a dynamic segment, add a constraint that overrides this – for example, id: /[^/]+/ allows anything except a slash.

1
  • My routes are generated routes using resources. Is the constraint still possible?
    – lulalala
    Commented May 15, 2014 at 8:28
1

Note that the accepted answer (adding a constraint that allows dots) unfortunately breaks your format. For example, if you want to support both http://example.com/sites/1-blau.de and http://example.com/sites/1-blau.de.json, the second will not be handled by rails as format: json. The :site_name will be the entire 1-blau.de.json. Uri encoding the dot as %2E gets handled differently by different browsers (Chrome will resolve %2E as a '.' whereas Firefox will keep it as %2E).

1
  • Thanks, I think it is a valid argument, and in such case I can only set contentType to application/json to avoid this.
    – lulalala
    Commented May 7, 2015 at 1:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.