[筆記] 在 Ruby on Rails 裡做簡單的 IP 過濾
目的:你應該不希望還在 Development 的時候被人家看光光。
做法如下,加在 app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
# 指定要在 development 才過濾 IP
before_filter :filter_development_ip if ENV["RAILS_ENV"] =~ /development/
# ... 中間可能有其他程式碼
private
# 以下的 method 要加在 private 後面
def filter_development_ip
if request.remote_ip =~ /^127\.0\.0\.1$/
true # allow access
else
head(403) # send 403 Forbidden header
end
end
end
IP 的部份是以 Regular Expression 配對來檢驗的,通過 Regular Expression 的配對,表示合法 IP。以上範例是限定只有 127.0.0.1 這個 IP 可以連線。
這項設定適用於 mod_rails 與 mongrel_rails。
當然你可以設防火牆。
參考:
- [RoR] 利用 before_filter 的簡單存取控制 – IT邦幫忙::IT知識分享社群:
- How to obtain the IP address of the current user | kev.in:



[...] https, Ruby on Rails, SSL « [lag] 原來 WordPress.com 可以放彩色的程式碼 [筆記] 在 Ruby on Rails 裡做簡單的 IP 過濾 [...]
[攻略] Ruby on Rails 與 SSL (https) « YORKXIN×YORKXIN
2009 年 一月 17 日 星期六 at 15:06:00