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

前端 未结 7 2009
無奈伤痛
無奈伤痛 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:34

    While John's answer is perfectly fine, if you are using Rails >= 2.3 I would suggest to create a new Metal. Rails Metals are more efficient and they offers better performance.

    $ ruby script/generate metal NotWwwToWww
    

    Then open the file and paste the following code.

    # Allow the metal piece to run in isolation
    require(File.dirname(__FILE__) + "/../../config/environment") unless defined?(Rails)
    
    class NotWwwToWww
      def self.call(env)
        if env["HTTP_HOST"] != 'www.example.org'
          [301, {"Content-Type" => "text/html", "Location" => "www.#{env["HTTP_HOST"]}"}, ["Redirecting..."]]
        else
          [404, {"Content-Type" => "text/html"}, ["Not Found"]]
        end
      end
    end
    

    Of course, you can customize further the Metal.

    If you want to use Apache, here's a few configurations.

提交回复
热议问题