将非 www 请求重定向到 Ruby on Rails 中的 www URL

问题描述:

这是一个简单的问题,但我似乎无法通过快速谷歌搜索找到答案.

It is a simple issue, but I can't seem to find an answer doing some quick googling.

Ruby on Rails 直接执行此 301 的方式是什么(http://x.com/abc> http://www.x.com/abc).before_filter?

What's the Ruby on Rails way of doing this 301 direct (http://x.com/abc > http://www.x.com/abc). A before_filter?

理想情况下,您应该在 Web 服务器(Apache、nginx 等)配置中执行此操作,这样请求甚至根本不会触及 Rails.

Ideally you'd do this in your web server (Apache, nginx etc.) configuation so that the request doesn't even touch Rails at all.

将以下 before_filter 添加到您的 ApplicationController:

Add the following before_filter to your ApplicationController:

class ApplicationController < ActionController::Base
  before_filter :add_www_subdomain

  private
  def add_www_subdomain
    unless /^www/.match(request.host)
      redirect_to("#{request.protocol}x.com#{request.request_uri}",
                  :status => 301)
    end
  end
end

如果您确实想使用 Apache 进行重定向,则可以使用:

If you did want to do the redirect using Apache, you could use this:

RewriteEngine on
RewriteCond %{HTTP_HOST} !^www\.x\.com [NC]
RewriteRule ^(.*)$ http://www.x.com/$1 [R=301,L]