转自:http://www.iteye.com/topic/419100
二级域名支持是一个很简单的问题,把JavaEye的代码贴出来供你参考:
# show website homepage
def homepage
if www?
render :template => 'main/homepage', :layout => false
elsif app?
if logged_in?
render :template => 'app/base/index', :layout => 'app'
else
redirect_to homepage_url
end
elsif job?
render :template => 'job/homepage', :layout => 'job'
elsif channel?
@channel = request.subdomains[0]
if File.exists?("#{RAILS_ROOT}/app/views/channel/#{@channel}/index.rhtml")
render :template => "channel/#{@channel}/index", :layout => 'channel'
else
render :file => "#{RAILS_ROOT}/public/404.html", :status => 404
end
elsif blog?
@blogs = @blog_owner.blogs_by_page params[:page]
render :template => 'blog/index/index', :layout => 'blog'
elsif group?
Group.increment_counter(:visit_count, @group.id)
render :template => 'group/index/index', :layout => 'group'
else
redirect_to homepage_url
end
end
------------------------------------------------------------------------------------
protected
def www?
return request.subdomains && request.subdomains[0] && request.subdomains.length == 1 && request.subdomains[0] == 'www'
end
def job?
return request.subdomains && request.subdomains[0] && request.subdomains.length == 1 && request.subdomains[0] == 'job'
end
def app?
return request.subdomains && request.subdomains[0] && request.subdomains.length == 1 && request.subdomains[0] == 'app'
end
def channel?
return request.subdomains && request.subdomains[0] && request.subdomains.length == 1 && RESERVED_DOMAIN.include?(request.subdomains[0])
end
判断一下subdomains,根据不同的域名做不同的处理,就这么简单。
我的作法也是参考了你n年前的只言片语写的,这回算是有幸见着原装的了。
有一个问题,就是比较关键的 blog? 方法能放上来吗?
还有一个问题,就是如:http://netfork.iteye.com/blog/XXX这样的效果似乎上面的代码并没有给出实现方法吧。
def blog?
if request.subdomains && request.subdomains[0] && request.subdomains.length == 1 && !RESERVED_DOMAIN.include?(request.subdomains[0])
@blog_owner ||= User.find_by_domain(request.subdomains[0])
return !@blog_owner.nil?
end
return false
end
def group?
if request.subdomains && request.subdomains[1] && request.subdomains[1].eql?("group") && request.subdomains.length == 2
@group ||= Group.find_by_domain request.subdomains[0]
return !@group.nil? && @group.active?
end
return false
end
/blog/xxx 就是标准的Rails路由映射,只不过这种controller需要加一个filter去判断进来的域名,如果不是博客域名访问过来的话就要redirect。
before_filter :blog_domain_required, :except => [:rss_blog, :show]
def blog_domain_required
redirect_to homepage_url and return false unless blog?
end