【问题标题】:Ruby on Rails redirecting www. to non-www version of siteRuby on Rails 重定向 www。到网站的非 www 版本
【发布时间】:2014-03-06 21:06:59
【问题描述】:

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

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

【问题讨论】:

    标签: ruby-on-rails redirect ruby-on-rails-4


    【解决方案1】:

    在您的应用程序控制器中:

    before_filter :redirect_subdomain
    
    def redirect_subdomain
      if request.host == 'www.puppies.com'
        redirect_to 'http://puppies.com' + request.fullpath, :status => 301
      end
    end
    

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

    编辑:为 SEO 使用永久重定向状态 (301)(如 @CHawk 建议的那样),如果是临时的,则使用 307。

    【讨论】:

    • 您可以使用全局变量,例如:redirect_to Rails.application.config.action_mailer.asset_host + request.fullpath 而不是硬编码的 URL,但请记住根据要求在生产或开发文件中定义它。跨度>
    • 是的。或者只是从主机字符串中删除www.(如果存在),然后重定向到新构建的网址。
    • 我们也可以与多租户站点一起使用,我们需要创建虚拟子域并需要限制一些子域,例如 www 邮件
    • 出于 SEO 目的,您应确保指定重定向为 301:redirect_to 'http://puppies.com' + request.fullpath, :status => 301
    【解决方案2】:

    为了完整起见,您可以使用 rails 的路由配置在 Rails 4 中使用 request-based routing constraints 来执行此操作

    与使用您的应用程序控制器相比,这种方式有一点性能优势,因为请求不需要访问您在 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
    

    【讨论】:

    • 这可能是match '(*any)', to: redirect(subdomain: ''), via: :all, constraints: {subdomain: 'www'}
    【解决方案3】:

    在您的应用程序控制器中:

      before_action :redirect_from_www_to_non_www_host
    
      def redirect_from_www_to_non_www_host
        domain_parts = request.host.split('.')
        if domain_parts.first == 'www'
          redirect_to(request.original_url.gsub('www.', ''), status: 301) and return  
        end
      end
    

    【讨论】:

    • 删除所有“www”实例。从整个 URL 听起来是个坏主意。如果有人在搜索表单中输入了 URL,或者您在 URL 中使用了 UUID,该怎么办?
    【解决方案4】:

    这可以通过多种方式实现。如果您使用 nginx 或 apache 来前端应用程序,请查看 url rewrite。

    在这里查看我的答案

    Is it possible to redirect a url that uses HTTPS protocol? (Heroku, Rails)

    【讨论】:

      猜你喜欢
      • 2010-12-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多