Nginx Block Directory Access but Allow Internal Access for Rewrites
By Shay Anderson on November 2013
I recently came across a situation where I needed to block external/public access to a directory on a nginx Web server, but I needed to allow rewrites (particularly PHP rewrites) to work in the protected directory. Here is an example, I need this type of request blocked: /src/something.php (block)But, I need a request like: /page/something.php (allow)rewritten so it directs the request internally to: /src/something.php (internal => allow)After much troubleshooting, and being more experience with Apache, I came up with a solution.
First, I am using PHP-FPM with nginx, so I separate the PHP-FPM / FastCGI logic in a separate file, I create the file /etc/nginx/php.conf and add the following: try_files $uri =404;
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
#fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;
include fastcgi_params;Next, in my nginx virtual hosts configuration file (/etc/nginx/conf.d/default.conf) I add the following lines to protect my src directory from public requests: location /src {
internal;
location ~ ^/src(.*\.php)$ {
include php.conf;
}
}And down below these lines I also include a *.php block: location ~ \.php$ {
include php.conf;
}
This works because as soon as a public request comes in as /src/* it is blocked (or not found) because of the internal syntax. However, I still need my PHP files to work for internal requests, and therefore I include my location ~ ^/src(.*\.php)$ block. If I didn’t include this block then nginx would use the last *.php block in the config file, which wouldn’t block public PHP requests in the src directory.
http://www.shayanderson.com/linux/nginx-block-directory-access-but-allow-internal-access-for-rewrites.htm