开发者

redirect 301 subdomains to users own urls in rails 3

I have a rails app that gives users a subdomain for their site. Users can then point their own domain to this sub domain to make it look like their own site.

When i user enters a domain name into my app i need to redirect any future requests to there subdomain url on my app to their own domain, also passing the path eg company_site.hosted_site.com/pages/about_us redirects to www.company_site.com/pages/about_us.

Does anyone know how to do this in rails 3 ?

I cant so it using apache rules as need to hit the database to get redirect url and also dont want to change开发者_开发问答 the conf file per users/subdomain.

Anyone done this ? ssems might be best done in rack middleware ? any ideas?

thanks alot Rick


A simple way is to do this in a before_filter block for ApplicationController so that all actions are affected by it:

before_filter :redirect_to_custom_domain

def redirect_to_custom_domain
  if (customer = Customer.find_by_subdomain(request.host))
    if (customer.domain?)
      # Redirects to the customer's full domain
      redirect_to(customer.domain_url)

      # Returning false will halt additional processing for this request
      return false
    end
  end
end

Customer would be your record where you store the assigned subdomain and an optional custom domain that they will be redirected to if it is specified.

In your Customer record you might have something like this as a helper method:

def Customer < ActiveRecord::Base
  def domain_url
    "http://#{domain}/"
  end
end
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜