nginx restrict directory access by ip

I'm using nginx and want to restrict access to a directory to everyone except myself. I want to access the php scripts in /restricted. I've tried a few things so far. If I recall, this works to block access to all except the allowed ip, but all scripts are pushed to download instead of processed now.

location ~ /restricted { allow 1.2.3.4; deny all; }


Solution 1:

You'll need a second (I prefer nested) php block since you want these php files handled differently. Also, assuming that /restricted is supposed to be a uri prefix and not just something that appears anywhere in the uri, you want a different type of location:

# This handles everything that starts with /restricted,
# and no regex locations will override it
location ^~ /restricted {
  allow 1.2.3.4;
  deny all;

  # This will inherit the allow/deny from the outer location
  location ~ \.php$ {
    include fastcgi.conf;
    fastcgi_pass backend;
  }
}