【问题标题】:Redirect domain to www.domain with Rails使用 Rails 将域重定向到 www.domain
【发布时间】:2026-02-10 18:40:01
【问题描述】:

你好, 我是 Ruby on Rails 的新手,我想添加一些属性以自动将我的 domain.com 重定向到 www.domain.com

我查看了存在的已关闭问题,但一切都可以使用 .htaccess,但我没有使用 Rails。

编辑:

看到这个链接:Redirect non-www requests to www urls in Rails 但似乎没有更新,我使用答案中的代码得到了这个错误(request_uri not found)

编辑二

来自http://apidock.com/rails/ActionDispatch/Http/URL/request_uri我看到我们现在必须使用request.url

使用以下代码尝试并得到错误的 URL:

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.url}",
                  :status => 301)
    end
  end
end

我的域名也变得陌生

【问题讨论】:

    标签: ruby-on-rails web


    【解决方案1】:

    我发现自己,下面的代码将添加 www。如果没有进入你的网址。

    class ApplicationController < ActionController::Base
      before_filter :add_www_subdomain
    
      private
      def add_www_subdomain
        unless /^www/.match(request.host)
          redirect_to("#{request.url}".gsub("#{request.protocol}", "#{request.protocol}www."), status: 301)
        end
      end
    end
    

    【讨论】: