在rails上使用htaccess密码保护?

我想通过使用.htaccess密码文件来保护我的rails应用程序上的/ admin路由 – 这可能吗?

Rails有一个内置的帮助器,你可以把它放在你的应用程序控制器中:

protected def authenticate authenticate_or_request_with_http_basic do |username, password| username == "admin" && password == "test" end end 

然后在要保护的任何控制器上使用before_filter(或者只是将其粘贴在应用程序控制器中以阻止整个站点):

 before_filter :authenticate 

这个方法适用于Nginx以及Apache,这是一个额外的好处。 但是,如果您启用了完整页面缓存,则它不起作用 – 因为访问者永远不会访问Rails堆栈; 它不会开始。

编辑只是注意到您指定了/ admin路由。 我的所有管理员控制器都从AdminControllerinheritance。 你可以这样设置你的:

/app/controllers/admin/admin_controller.rb

 class Admin::AdminController < ApplicationController before_filter :authenticate protected def authenticate authenticate_or_request_with_http_basic do |username, password| username == "admin" && password == "test" end end end 

然后让所有控制器扩展管理控制器,例如:

 class Admin::ThingsController < Admin::AdminController 

我的路线设置如下:

 map.namespace :admin do |admin| admin.resources :things end 

希望有所帮助。

Interesting Posts