Nginx PHP-FPM Basic Auth

http-basic-authenticationnginxphp-fpm

I have nginx with php-fpm installed on Debian Squeeze.
Directory tree is:

  • /var/www/mysite
    • index.php
    • secret_folder_1
      • admin.php
      • static.html
    • secret_folder_2
      • admin.php
      • static.html
    • pictures
    • img01.jpg

I need to close secret_folder_1 and secret_folder_2 with basic_auth.
Now config looks like:

location ~ /secret_folder_1/.+\.php$
{
        root /var/www/mysite/;
        fastcgi_pass   127.0.0.1:9000;
        fastcgi_param  SCRIPT_FILENAME  /var/www/mysite$fastcgi_script_name;
        include        fastcgi_params;
        auth_basic "Restricted Access";
        auth_basic_user_file /path/to/.passwd;
}

location ~ /secret_folder_1/.*
{
        root /var/www/mysite/;
        auth_basic "Restricted Access";
        auth_basic_user_file /path/to/.passwd;
}

Same config for secret_folder_2.

Is it normal? I mean, first location for serving php files in restricted folder, and second location for serving static files.

Can it be simplified?

Best Answer

The nested locations may be better:

location /secret_folder_1 {
    root /var/www/mysite/;
    auth_basic "Restricted Access";
    auth_basic_user_file /path/to/.passwd;

    location ~* \.php$ {
        fastcgi_pass   127.0.0.1:9000;
        include        fastcgi.conf;
    }
}

Please notice that you should define SCRIPT_FILENAME parameter with $document_root variable instead of hardcoded /var/www/mysite/:

fastcgi_param  SCRIPT_FILENAME    $document_root$fastcgi_script_name;