Question about multiple applicable locations in a server config

Jonathan Matthews contact at jpluscplusm.com
Thu Jun 13 20:48:33 UTC 2013


On 13 June 2013 20:31, John Barton <jbarton at conquerthe.net> wrote:
> I have read documentation from several sources, and there is still 1 detail
> about nginx configuration that I do not fully understand, and would like
> some additional guidance. In the nginx location configuration, how does one
> handle locations that would match multiple criteria, but nginx can only
> match on one?
> For example, lets say I have a php application and I am using php-fpm, which
> has an admin interface that I want to protect using htaccess. I would have
> location directives in my config with the following contents:
>
> location ~* /admin/ {
>   auth_basic "Restricted";
>   auth_basic_user_file htpasswd;
> }
>
> location ~* \.php$ {
>   try_files $uri =404;
>   fastcgi_index index.php;
>   fastcgi_pass unix:/var/run/php-fpm/php-fpm.sock;
>   include fastcgi_params;
>   fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
>   fastcgi_param SCRIPT_NAME $fastcgi_script_name;
> }
>
>
> From my understanding of how nginx processes the config file, it would match
> the /admin/ regex first, but what if the files contained in this directory
> are PHP scripts? Since the first location matches in my config, I believe
> that the second location with the PHP redirect is never processed?

Remember you can use nested location. I would imagine (though haven't
tested) that this will work:

---------------------------------
location ~ \.php {
 try_files $uri =404;
 fastcgi_index index.php;
 fastcgi_pass unix:/var/run/php-fpm/php-fpm.sock;
 include fastcgi_params;
 fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
 fastcgi_param SCRIPT_NAME $fastcgi_script_name;

 location ~ /admin/ {
  auth_basic "Restricted";
  auth_basic_user_file htpasswd;
 }
}
---------------------------------

Regards,
Jonathan
--
Jonathan Matthews // Oxford, London, UK
http://www.jpluscplusm.com/contact.html



More information about the nginx mailing list