如何在nginx的sublocations中全局使用FastCGI和Basic Auth?

我最近部署了我的第一个nginx安装程序,一切工作真的很好,除了位置parsing驱使我疯了。 我有一个简单的PHP fastcgi设置像这样:

location ~ \.php { if (!-e $request_filename) { return 404; } include /etc/nginx/fastcgi.conf; keepalive_timeout 0; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; fastcgi_pass 127.0.0.1:9000; } 

现在我想要像这样使用基本身份validation来保护一些位置:

  location /madmin { auth_basic "Restricted"; auth_basic_user_file /var/www/localhost/admincp/.htpasswd; } 

在他的设置下,nginx在/ madmin时要求input密码,但是不会在/madmin/foo.php中提问。 如果我将auth位置更改为“location〜^ / madmin”,那么nginx会为php文件下载…

是不是可以在nginx中configuration多个位置? 如果没有,这里的解决方法是什么?

谢谢你的帮助。

请参阅http://nginx.org/en/docs/http/request_processing.html获取关于nginx如何处理请求(包括位置)的说明。 维基文档也有一些很好的例子。 不幸的是,目前没有logging的function是你最想要的。

如前所述,只有一个位置在NginX中获胜。 但是,您可能不知道nginx支持位置内的位置。 所以你的位置策略可能实际上就像这个示例服务器(fastcgi.conf在0.8.31以上):

 upstream my-backend { localhost:9000; } server { listen 80; server_name my-awesome-php.site; root /path/to/root; # The protected location location /protected { auth_basic "Give me codes."; auth_basic_user_file /path/to/.htpasswd; location ~ \.php$ { include fastcgi.conf; fastcgi_pass my-backend; } } # Normal files (blank location is OK, just means serve from root) location / { } # PHP for normal stuff location ~ \.php$ { include fastcgi.conf; fastcgi_pass my-backend; } } 

原因是因为nginx将select最具体的位置块可用。 正则expression式匹配的位置将胜过纯string匹配。

所以当你有/ madmin的请求时,它与你的authentication位置相匹配,但是以.php结尾的任何内容都会先到达。

定位〜^ / madmin服务php代码而不parsing的原因是因为如果下面的正则expression式匹配,^ ^停止search。

你可以在这里看到位置文档: http : //wiki.nginx.org/NginxHttpCoreModule#location

这似乎解决了这个问题,但它看起来真的很多与位置指令,我认为即使是静态文件现在由php-fastcgi服务,但它可以通过重写“如果指令,我猜。

 location ~ ^/madmin { auth_basic "Restricted Access"; auth_basic_user_file /var/www/localhost/admincp/.htpasswd; include /etc/nginx/fastcgi.conf; fastcgi_pass 127.0.0.1:9000; }