Skip to content

Instantly share code, notes, and snippets.

@omarramos
Forked from moiristo/gist:1245170
Created January 30, 2012 22:02
Show Gist options
  • Save omarramos/1707067 to your computer and use it in GitHub Desktop.
Save omarramos/1707067 to your computer and use it in GitHub Desktop.
Rails3 way to redirect non-www domain to www domain
# Rails3 way to redirect non-www domain to www domain
# Single domain redirect
'example.com'.tap do |host|
constraints(:host => host) do
root :to => redirect {|params, req| URI.escape(req.query_string.present? ? "#{req.protocol}www.#{host}?#{req.query_string}" : "#{req.protocol}www.#{host}") }
match '/*path', :to => redirect {|params, req| URI.escape(req.query_string.present? ? "#{req.protocol}www.#{host}/#{params[:path]}?#{req.query_string}" : "#{req.protocol}www.#{host}/#{params[:path]}") }
end
end
# Multiple domain redirect
['host-1.com', 'host-2.com'].each do |host|
constraints(:host => host) do
root :to => redirect {|params, req| URI.escape(req.query_string.present? ? "#{req.protocol}www.#{host}?#{req.query_string}" : "#{req.protocol}www.#{host}") }
match '/*path', :to => redirect {|params, req| URI.escape(req.query_string.present? ? "#{req.protocol}www.#{host}/#{params[:path]}?#{req.query_string}" : "#{req.protocol}www.#{host}/#{params[:path]}") }
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment