Rails:重定向到当前路径但不同的子域

我认为这应该相当容易,但我不熟悉它是如何完成的……

你如何编写一个filter,用于检查当前请求是否针对某些子域,如果是,则将其重定向到同一个URL但是在不同的子域上?

即: blog.myapp.com/posts/1很好,但blog.myapp.com/products/123重定向到www.myapp.com/products/123

我在想像……

 class ApplicationController < ActionController::Base before_filter :ensure_domain protected def ensure_domain if request.subdomain == 'blog' && controller_name != 'posts' redirect_to # the same url but at the 'www' subdomain... end end end 

你怎么写那个重定向?

ActionController ::重定向#redirect_to允许您传递绝对URL,因此最简单的方法是将其传递给:

 redirect_to request.url.sub('blog', 'www') 

从子域重定向到子域的简单选择如下

 redirect_to subdomain: 'www', :controller => 'www', :action => "index" 

这将在域名上调用,例如foo.apple.com将转到www.apple.com