I'm working on a Ruby on Rails app where my routes can properly handle something like http://localhost:3000/CA
to go to some page about California. It handles lower case "ca" but is there a way such that if my user manually types in lower case "ca", the URL/Routes will display capital "CA"?
2 Answers
If user request for http://localhost:3000/ca
it should redirect to (301 redirect) http://localhost:3000/CA
,
That you can handle in your controller
def controller_name
if(params[:id].to_s != params[:id].to_s.upcase)
redirect_to urlname_url(:params[:url].to_s.upcase), :status => :moved_permanently
end
# rest of the code
end
It is good to have unique urls as duplicate urls have negative impact on SEO.

- 120
- 8
-
Is there a global config (or a default regexp to specify in a constraint) to do that ? – Ben Mar 05 '15 at 12:35
You can use a route matching to redirect to a capitalized version of the desired route.
I don't know what your routes file looks like so I will provide you with a simplified version of something I came up with that you can use to build what you need.
Say I have a states
controller that has an action for every single state abbreviation. I could declare my route like this (for the get
action StatesController#ca (for California)):
get '/CA', to: 'states#ca'
This would only match capitalized CA, so if a user typed http://localhost:3000/ca
, they would get an error. To resolve this, I could match '/ca' to '/CA':
get '/ca', to: redirect('/CA')
This is very simplified. It is very unlikely you will want to describe every state abbreviation explicitly in your routes file.
Again, I don't know what you are using in your routes file, so I can only tell you (rather than show you an example) that you can provide a block to handle this logic.
Using a block you could also create logic that will handle cases when people inconsistently capitalize the abbreviation as well (Like transformingcA
or Ca
to CA
).
There is some helpful / related documentation here: http://guides.rubyonrails.org/routing.html#redirection .

- 5,792
- 5
- 43
- 89
-
Note that this form of redirect should work, but involves an extra round trip and associated latency (you return a "301 moved permanently" to the browser and it typically retries at the new address). Since it only happens the first time the user manually enters the URI (and is presumably clicking links thereafter) it's not too bad. – Russ Ennis Mar 11 '14 at 14:25