I would like to redirect from a directory to a subdomain in Ruby on Rails.
As it is, it goes to slug.example.com
. How can I redirect it to xxx.example.com
?
# slug = 'xxx'
get '/users/:slug', to: redirect(subdomain: 'slug', path: '')
CodePudding user response:
You have to use a block as documented in https://guides.rubyonrails.org/routing.html#redirection and https://api.rubyonrails.org/v6.1.4/classes/ActionDispatch/Routing/Redirection.html#method-i-redirect.
But proably hte easiest way is to subclass the existing OptionRedirect class:
class SubdomainFromSlugRedirect < ActionDispatch::Routing::OptionRedirect
# something that won't appear in your routes
SUBDOMAIN_TOKEN = 'qwertyuiopasdfghjklzxcvbnm'
def options
super.merge(subdomain: SUBDOMAIN_TOKEN)
end
def path(params, _request)
super.sub(SUBDOMAIN_TOKEN, params[:slug])
end
end
and then use it in the router
get '/users/:slug', to: redirect(SubdomainFromSlugRedirect)