Home  >  Q&A  >  body text

ruby - rails限制多个IP访问的方法?

对某一个action的IP的限制方式是,在routes.rb中:

  constraints(:ip => Settings.ip.allow) do
     post '/somecontroller/callback', to: 'somecontroller#callback' , as: 'somecontroller_callback'
  end

在settings.yml中:

  ip:
    allow: '127.0.0.1'

这是可以的.

但是想对多个IP允许访问,在settings.yml中如下:

  ip:
    allow: '/127.0.0.1|127.0.0.2/'

却不行。哪里不对呢?

黄舟黄舟2762 days ago606

reply all(1)I'll reply

  • 黄舟

    黄舟2017-04-21 11:00:01

    Because Settings.ip.allow always returns String, but in fact, in the second case, what you need is a RegExp, so it is invalid. You can try changing it like this:

    config/routes.rb:

    constraints(:ip => %r{#{Settings.ip.allow}}) do
     post '/somecontroller/callback', to: 'somecontroller#callback' , as: 'somecontroller_callback'
    end
    

    config/settings.rb

    ip:
      allow: '127.0.0.1|127.0.0.2'
    

    reply
    0
  • Cancelreply