ruby on rails, restricting access to public directory
I need to prevent access to public directory with .htaccess kind of mechanism. It means that hitting http://localhost:3000 should ask for credentials before it shows anything else. Is it possible?
You could achieve something similar by using a before_filter
in your ApplicationController. Be aware that this is only adding authentication to all of your controller actions, it won't protect the sub-directories of public like stylesheets, javascripts and images. If for some reason that's what you're looking for, you should probably just use the htpasswd method.
Railscasts: http://railscasts.com/episodes/82-http-basic-authentication - just put the before_filter
and authenticate
stuff in your ApplicationController to protect every controller.
Basic authentication just at production for example:
In the application_controller.rb:
USERNAME = 'foo'
PASSWORD = 'bar
if RAILS_ENV['production']
before_filter :authenticate
end
private
def authenticate
authenticate_or_request_with_http_basic do |user_name, password|
user_name == USERNAME && password == PASSWORD
end
end
精彩评论