How to use FastCGI globally and Basic Auth in sublocations in nginx?

Solution 1:

Please see http://nginx.org/en/docs/http/request_processing.html for a description of how nginx handles a request, including locations. The wiki documentation also has some good examples. Unfortunately, a currently undocumented feature is what you want here, most likely.

As mentioned previously, only one location wins in NginX; however, you may not know that nginx supports locations within locations. So your location strategy might actually be like this example server (fastcgi.conf in 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;
  } 

}