Nginx deny doesn't work for folder files

Ubertone asked:

I’m trying to restrict access to my site to allow only specific IPs and I’ve got the following problem: when I access deny works perfectly, but when I try to access it returns “Access denied” page AND php file is downloaded directly in browser without processing.
I do want to deny access to all the files on the website for all IPs but mine. How should I do that?

Here’s the config I have:

server {
listen 80;
root /var/www/example;

location / {
    index index.html index.php; ## Allow a static html file to be shown first
    try_files $uri $uri/ @handler; ## If missing pass the URI to front handler
    expires 30d; ## Assume all files are cachable
 allow my.public.ip;
 deny all;

location @handler { ## Common front handler
    rewrite / /index.php;
location ~ .php/ { ## Forward paths like /js/index.php/x.js to relevant handler
    rewrite ^(.*.php)/ $1 last;

location ~ .php$ { ## Execute PHP scripts
    if (!-e $request_filename) { rewrite / /index.php last; } ## Catch 404s that try_files miss

    expires        off; ## Do not cache dynamic content
    fastcgi_param  HTTPS $fastcgi_https;
    fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
    include        fastcgi_params; ## See /etc/nginx/fastcgi_params

My answer:

Your location @handler is completely unnecessary and redundant, and is probably the cause of the problem. This is already covered by your existing index and try_files directive. Remove the location entirely and fix try_files.

try_files $uri $uri/ /index.php;

View the full question and any other answers on Server Fault.

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.