Nginx sucessfully password protects PHP files, but then prompts you to download them

久未见 提交于 2019-12-01 23:31:21

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!