How can I use Rails routes to redirect from one domain to another?

老子叫甜甜 提交于 2019-11-27 12:26:53
Lukas Eklund

This works in Rails 3.2.3

constraints(:host => /foo.tld/) do
  match "/(*path)" => redirect {|params, req| "http://bar.tld/#{params[:path]}"}
end

This works in Rails 4.0

constraints(:host => /foo.tld/) do
  match "/(*path)" => redirect {|params, req| "http://bar.tld/#{params[:path]}"},  via: [:get, :post]
end

This does the job of the other answer. Though in addition, it preserves query strings as well. (Rails 4):

# http://foo.tld?x=y redirects to http://bar.tld?x=y
constraints(:host => /foo.tld/) do
  match '/(*path)' => redirect { |params, req|
    query_params = req.params.except(:path)
    "http://bar.tld/#{params[:path]}#{query_params.keys.any? ? "?" + query_params.to_query : ""}"
  }, via: [:get, :post]
end

Note: If you're dealing with full domains instead of just subdomains, use :domain instead of :host.

zelanix

The following solution redirects multiple domains on GET and HEAD requests while returning http 400 on all other requests (as per this comment in a similar question).

/lib/constraints/domain_redirect_constraint.rb:

module Constraints
  class DomainRedirectConstraint
    def matches?(request)
      request_host = request.host.downcase
      return request_host == "foo.tld1" || \
             request_host == "foo.tld2" || \
             request_host == "foo.tld3"
    end
  end
end

/config/routes.rb:

require 'constraints/domain_redirect_constraint'

Rails.application.routes.draw do
  match "/(*path)", to: redirect {|p, req| "//bar.tld#{req.fullpath}"}, via: [:get, :head], constraints: Constraints::DomainRedirectConstraint.new
  match "/(*path)", to: proc { [400, {}, ['']] }, via: :all, constraints: Constraints::DomainRedirectConstraint.new

  ...
end

For some reason constraints Constraints::DomainRedirectConstraint.new do didn't work for me on heroku but constraints: Constraints::DomainRedirectConstraint.new worked fine.

Bit more modern approach:

constraints(host: 'www.mydomain.com') do
    get '/:param' => redirect('https://www.mynewurl.com/:param')
end
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!