Nginx sucessfully password protects PHP files, but

2020-04-14 10:37发布

问题:

In a previous question, I was trying to password protect my /admin/ and sub-folders directory using Nginx with .htpasswd and regex.

That was done successfully, but now, after password authentication was completed, Nginx prompts to "download" php files, rather than simply loading them.

This doesn't happen when the new location "authentication" block is commented out. For instance, in this code sample, PHP pages load without any issue:

    location / {
            try_files $uri $uri/ =404;
    }

    #location "~^/admin/.*$" {
    #       try_files $uri $uri/ =404;
    #       auth_basic "Restricted";
    #       auth_basic_user_file /etc/nginx/.htpasswd;
    #}

    location ~ \.php$ {
            try_files $uri =404;
            fastcgi_split_path_info ^(.+\.php)(/.+)$;
            fastcgi_pass unix:/var/run/php/php7.0-fpm.sock;
            fastcgi_index index.php;
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
            include fastcgi_params;
    }

How can I resolve these (apparently conflicting) location blocks, so the /admin/ section is password protected yet php files still load?

回答1:

The problem is a fundamental misunderstanding as to how nginx processes a request. Basically, nginx chooses one location to process a request.

You want nginx to process URIs that begin with /admin in a location block that requires auth_basic. In addition, URIs that end with .php need to be sent to PHP7.

So you need two fastcgi blocks, one to process normal PHP files and one to process restricted PHP files.

There are several forms of location directive. You have already discovered that the regex locations are ordered and therefore your location "~^/admin/.*$" block effectively prevents the location ~ \.php$ block from seeing any URI beginning with /admin and ending with .php.

A clean solution would be to use nested location blocks and employ the ^~ modifier which forces a prefix location to take precedence over a regex location:

location / {
    try_files $uri $uri/ =404;
}

location ~ \.php$ {
    try_files $uri =404;

    include fastcgi_params;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    fastcgi_pass unix:/var/run/php/php7.0-fpm.sock;
}

location ^~ /admin/ {
    auth_basic "Restricted";
    auth_basic_user_file /etc/nginx/.htpasswd;

    try_files $uri $uri/ =404;

    location ~ \.php$ {
        try_files $uri =404;

        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_pass unix:/var/run/php/php7.0-fpm.sock;
    }
}

Note that location ^~ is a prefix location and not a regex location.

Note also that the fastcgi_split_path_info and fastcgi_index directives are not required in a location ~ \.php$ block.