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

后端 未结 6 1013
栀梦
栀梦 2020-12-02 23:59

My app used to run on foo.tld but now it runs on bar.tld. Requests will still come in for foo.tld, I want to redirect them to bar.tld.

How can I do this in rails rou

6条回答
  •  无人及你
    2020-12-03 00:26

    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.

提交回复
热议问题