Had the same issue!
Found the answer here, http://www.ceus-now.com/nginx-password-protect-directory-downloads-source-code/
Because we are adding ^~ we are leaving behind some other settings (not sure why we need to add this but it was the only way to get it to actually pull up the authentication :( )
include /etc/nginx/fastcgi_params;
fastcgi_pass unix:/var/lib/php5-fpm/web11.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_intercept_errors on;
I tried various combinations to see what was/not needed and each line is needed. I wish I understood these things better.
UPDATE: July 27th 2016:
So I did some reading and finally understand why we have this issue.
In short when we install FastCGI and php-fpm it creates a directive in the nginx server files (which file depends on your server install).
So in mine I have the following...
location ~ \.php$ {
include snippets/fastcgi-php.conf;
#
# # With php7.0-cgi alone:
# fastcgi_pass 127.0.0.1:9000;
# # With php7.0-fpm:
fastcgi_pass unix:/run/php/php7.0-fpm.sock;
As you will notice these directives are in location / and not in the global settings. Since we want to secure a particular folder these directives are not inherited. Therefore, we need to declare it again.
If we wanted to follow the DRY ("Don't Repeat Yourself") principle, then we would declare the PHP-fpm and FastCGI in the global settings. We can do this by moving it to below (example, but it just needs to be outside of location directive). Here is an example.
root /var/www/html;
fastcgi_param REQUEST_METHOD $request_method;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_index index.php;
Hope this helps. I realized the above by reading https://www.digitalocean.com/community/tutorials/understanding-and-implementing-fastcgi-proxying-in-nginx
Disclaimer: I am no pro so if you see mistakes be nice and just let me know and I will hopefully update.
I added this to the server block and it works:
add_header Allow "GET, POST, PUT, DELETE, HEAD" always;
valid_referers none blocked server_names *.example.com;
if ($request_method !~ ^(GET)$ ) {
set $req A;
}
if ($invalid_referer) {
set $ref "${req}A";
}
if ($ref = AA) {
return 403;
}
Best Answer
You should use
limit_except
:It works since nginx 0.8.48, in older versions there was a bug where
fastcgi_pass
was not inherited inside the limit_except block.