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

前端 未结 9 2075
北荒
北荒 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 20:06

    Nothing wrong with the approaches above, but there are also a couple of gems that provide Rack middleware to do this.

    I like the way that they keep this behaviour separate from the app itself, but it's not a particularly strong argument either way. I also use middleware to do this when working with Sinatra, so prefer to use a technique that I can use on apps built from Rails and/or Sinatra (I often run Nesta embedded in Rails).

    Anyway, here they are:

    • https://github.com/cwninja/rack-force_domain
    • https://github.com/tylerhunt/rack-canonical-host

    The first is simpler (and the one I've been using) while the second offers a couple more features (that I'm yet to need, but appreciate).

    0 讨论(0)
  • 2020-12-12 20:13

    In Ruby on Rails 4, removing www. from any URL whilst maintaining the pathname can be achieved simply by using:

    # config/routes.rb
    
    constraints subdomain: 'www' do
      get ':any', to: redirect(subdomain: nil, path: '/%{any}'), any: /.*/
    end
    

    In contrast, adding www. to the beginning of any URL that doesn't already have it can be achieved by:

    # config/routes.rb
    
    constraints subdomain: false do
      get ':any', to: redirect(subdomain: 'www', path: '/%{any}'), any: /.*/
    end
    
    0 讨论(0)
  • 2020-12-12 20:14

    If you want to redirect from the top-level domain (TLD) to the www subdomain, use this code:

    constraints :subdomain => '' do
      match '(*any)' => redirect { |p, req| req.url.sub('//', '//www.') }
    end
    

    Note: This code the use of sub, not gsub, because sub replaces the first occurrence of the double-slashes where gsub would replace all double-slashes.

    0 讨论(0)
提交回复
热议问题