Ruby on Rails重定向www.到非www版网站

Dob*_*swe 7 redirect ruby-on-rails ruby-on-rails-4

我想重定向www.版本到网站的非www版本,除非它是子域名.(例如:将www.puppies.com重定向到puppies.com,但不要重定向www.cute.puppies.com).

如何在保持完整请求路径的同时完成此操作?(例如:www.puppies.com/labradors转到puppies.com/labradors)

noe*_*oel 13

在您的应用程序控制器

before_filter :redirect_subdomain

def redirect_subdomain
  if request.host == 'www.puppies.com'
    redirect_to 'http://puppies.com' + request.fullpath, :status => 301
  end
end
Run Code Online (Sandbox Code Playgroud)

正如@isaffe指出的那样,您也可以在Web服务器中重定向.

编辑:使用永久重定向状态(301)进行搜索引擎优化(如@CHawk所建议)或307(如果是临时的).


Rob*_*Rob 6

为了完整起见,您可以使用 Rails 的路由配置在 Rails 4 中使用基于请求的路由约束来执行此操作

与使用应用程序控制器相比,这种方式具有很小的性能优势,因为请求不需要命中在 Rails 路由中间件期间处理的应用程序代码。

将以下内容放入您的路由文件 ( config/routes.rb)

例如:

Rails.application.routes.draw do

  # match urls where the host starts with 'www.' as long it's not followed by 'cute.'
  constraints(host: /^www\.(?!cute\.)/i) do 

    match '(*any)', via: :all, to: redirect { |params, request|

      # parse the current request url
      # tap in and remove www. 
      URI.parse(request.url).tap { |uri| uri.host.sub!(/^www\./i, '') }.to_s 

    }

  end

  # your app's other routes here...

end
Run Code Online (Sandbox Code Playgroud)