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

12,959

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;
  } 

}
Share:
12,959

Related videos on Youtube

Admin
Author by

Admin

Updated on November 19, 2022

Comments

  • Admin
    Admin over 1 year

    I recently deployed my first nginx setup and everything works really nice, except the location parsing is driving me nuts. I have a simple php fastcgi setup like this:

    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;
    }
    

    Now i want to secure some locations with basic auth like this:

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

    Witht his setup, nginx asks for a password when going to /madmin, but won't ask at /madmin/foo.php. If i change the auth location to something like "location ~ ^/madmin" then nginx serves php file for download ...

    isn't it possible to configure multiple locations in nginx? if not, what's the workaround here?

    Thanks for your help.

  • Faheem
    Faheem about 14 years
    yeah, i figured it from the documentation why php files are not interpreted anymore in the second case. but i have yet to find a proper solution to this problem. i'm going to try to include the php/fastcgi stuff in every location now, but this seems really hacky
  • Admin
    Admin almost 11 years
    Is there a solution that does not require to repeat the *.php configuration? It can be quite lengthy in some setups.
  • Admin
    Admin about 9 years
    @MichaelHärtl I dont know if the following solution fits nginx best practices, but you can move your *.php part to a separate file and include it multiple times in your config.