Nginx – php-fpm: access restrictions for some php pages

nginxPHPphp-fpm

I have a folder containing some PHP files served with php-fpm (fastcgi); inside tihs folder, I have a file which I want to be allowed for internal IPs and deny for external.

The problem I have is that with this configuration…

# PHP
location ~ ^\/some\/path\/(.*\.php)$ {
  alias /some/path/;
  fastcgi_split_path_info ^(.+\.php)(/.+)$;
  # # NOTE: You should have "cgi.fix_pathinfo = 0;" in php.ini
  #
  # # With php5-cgi alone:
  # fastcgi_pass 127.0.0.1:9000;
  # # With php5-fpm:
  fastcgi_pass unix:/var/run/php5-fpm.sock;
  fastcgi_index index.php;
  include fastcgi_params;
  # Changes due to the alias declaration
  fastcgi_param SCRIPT_FILENAME $document_root/$1;
  fastcgi_param SCRIPT_NAME /$1;
}

# PHP: phpinfo() access restrictions
location = /some/path/phpinfo.php {
  allow 10.0.0.0/24;
  deny all;
}

…access to /some/path/phpinfo.php is managed correctly but the fastcgi rules are not applied (I download the phpinfo.php file); while with this configuration…

# PHP
location ~ ^\/some\/path\/(.*\.php)$ {
  alias /some/path/;
  fastcgi_split_path_info ^(.+\.php)(/.+)$;
  # # NOTE: You should have "cgi.fix_pathinfo = 0;" in php.ini
  #
  # # With php5-cgi alone:
  # fastcgi_pass 127.0.0.1:9000;
  # # With php5-fpm:
  fastcgi_pass unix:/var/run/php5-fpm.sock;
  fastcgi_index index.php;
  include fastcgi_params;
  # Changes due to the alias declaration
  fastcgi_param SCRIPT_FILENAME $document_root/$1;
  fastcgi_param SCRIPT_NAME /$1;
}

# PHP: phpinfo() access restrictions
location ~ ^\/some\/path\/phpinfo\.php$ {
  allow 10.0.0.0/24;
  deny all;
}

/some/path/phpinfo.php is interpreted correctly but access restrictions are not applied.

How can I fix the configuration in order that /some/path/phpinfo.php gets interpreted and access restrictions are applied?

Best Answer

nginx only applies one location block at the same level, so it's either going to apply the first one (with the FastCGI but no access control) or the second one (with access control by no FastCGI). To have them both applied you need to nest them like so:

location ~ ^\/some\/path\/(.*\.php)$ {
    fastcgi_pass unix:/var/run/php5-fpm.sock;

    location /some/path/phpinfo.php {
        allow 10.0.0.0/24;
        deny all;
    }
}