简体   繁体   中英

rails redirect to same page but add subdomain

If a user is at

blah.com/items/index

how do I redirect them to

de.blah.com/items/index

in a way that will work for any page? Right now I'm using

<%= link_to 'German', root_url(:host => 'de' + '.' + request.domain + request.port_string) %>

but that redirects them to de.blah.com. How do I keep the rest of the url? I'm using rails 3.

把事情简单化:

redirect_to subdomain: 'de'
<%= link_to 'German', params.merge({:host => with_subdomain(:de)}) %>

in app/helpers/url_helper.rb

module UrlHelper
  def with_subdomain(subdomain)
    subdomain = (subdomain || "")
    subdomain = "" if I18n.default_locale.to_s == subdomain
    subdomain += "." unless subdomain.empty?
    [subdomain, request.domain(tld_length), request.port_string].join
  end

  def url_for(options = nil)
    if options.kind_of?(Hash) && options.has_key?(:subdomain)
      options[:host] = with_subdomain(options.delete(:subdomain))
    end
    super
  end

  def tld_length
    tld_length = case Rails.env
      when 'production' then 2
      when 'development' then 0
      else 0
    end
  end 
end

使用subdomain-fu插件可能被证明是有用的,它也可以作为gem使用。

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