Redirect non-www requests to www URLs in Ruby on Rails

前端 未结 7 1960
無奈伤痛
無奈伤痛 2020-12-01 09:52

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

What\'s the Ruby on Rails way of doing this 301 direct (http://x.com/abc > http:

相关标签:
7条回答
  • 2020-12-01 10:44

    There is a better Rails 3 way - put this in your routes.rb file:

      constraints(:host => "example.com") do
        # Won't match root path without brackets around "*x". (using Rails 3.0.3)
        match "(*x)" => redirect { |params, request|
          URI.parse(request.url).tap { |x| x.host = "www.example.com" }.to_s
        }
      end
    

    Update

    Here is how to make it domain agnostic:

      constraints(subdomain: '') do
        match "(*x)" => redirect do |params, request|
          URI.parse(request.url).tap { |x| x.host = "www.#{x.host}" }.to_s
        end
      end
    
    0 讨论(0)
提交回复
热议问题