How do I redirect without www using Rails 3 / Rack?

前端 未结 9 2074
北荒
北荒 2020-12-12 19:36

I understand there are a lot of questions that answer this. I\'m familiar with .htaccess and nginx.conf methods, but I do not have access to such t

相关标签:
9条回答
  • 2020-12-12 19:52

    Take a look at this middleware, it should do precisely what you want:

    http://github.com/iSabanin/www_ditcher

    Let me know if that worked for you.

    0 讨论(0)
  • 2020-12-12 19:54

    There's a better approach if you're using Rails 3. Just take advantage of the routing awesomeness.

    Foo::Application.routes.draw do
      constraints(:host => /^example.com/) do
        root :to => redirect("http://www.example.com")
        match '/*path', :to => redirect {|params| "http://www.example.com/#{params[:path]}"}
      end
    end
    
    0 讨论(0)
  • 2020-12-12 19:57

    In Rails 3

    #config/routes.rb
    Example::Application.routes.draw do
      constraints(:host => "www.example.net") do
        match "(*x)" => redirect { |params, request|
          URI.parse(request.url).tap { |x| x.host = "example.net" }.to_s
        }
      end
      # .... 
      # .. more routes ..
      # ....
    end
    
    0 讨论(0)
  • 2020-12-12 20:03

    I really like using the Rails Router for such things. Previous answers were good, but I wanted something general purpose I can use for any url that starts with "www".

    I think this is a good solution:

    constraints(:host => /^www\./) do
      match "(*x)" => redirect { |params, request|
        URI.parse(request.url).tap {|url| url.host.sub!('www.', '') }.to_s
      }
    end
    
    0 讨论(0)
  • 2020-12-12 20:05

    A one-line version of Duke's solution. Just add to the top of routes.rb

    match '(*any)' => redirect { |p, req| req.url.sub('www.', '') }, :constraints => { :host => /^www\./ }
    
    0 讨论(0)
  • 2020-12-12 20:06

    For Rails 4 the above solutions have to be appended with the Verb construction e.g. via: [:get, :post]. Duke's solution becomes:

      constraints(:host => /^www\./) do
        match "(*x)" => redirect { |params, request|
          URI.parse(request.url).tap {|url| url.host.sub!('www.', '') }.to_s
        }, via: [:get, :post]
      end
    
    0 讨论(0)
提交回复
热议问题