简体   繁体   中英

Redirect a subdomain to a subfolder in Rails

I know it should be better in ngnix, but I have to do it in Rails (routes.rb)

My old url is:

http:// country .example.com/whatever/whatever

New URL

http://example.com/ country /whatever/whatever

Original Answer

With constraint (Only apply if subdomain is country.example.com)

constraints :subdomain => "country" do
  get "programs/:id", to: redirect { |params, req| "http://#{req.domain}/#{req.subdomain}/programs/#{params[:id]}" }
end

Without constraint (Will apply to any subdomain, chicken.example.com, waffles.example.com)

get 'programs/:id', to: redirect { |params, req| "#{req.subdomain}/programs/#{params[:id]}" }

Edit to match all params

Route Globbing as specified here should it. This should work:

constraints :subdomain => "country" do
  get "*all", to: redirect { |params, req| "http://#{req.domain}/#{req.subdomain}/#{params[:all]}" }
end

Bascially it's just catching all parameters in params[:all] and using that to forward them. Be sure to wrap this in a subdomain constraint though as it could catch all of your get requests, depending on where it sits in your routes.rb file

Routes.rb

constraints :subdomain => /sweden|uk|finland/ do
    get "(*all)", to: redirect { |params, req| "http://#{req.domain}/#{req.subdomain}/#{params[:all]}" }
  end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM