I'm trying to make admin folder accessible just to users reaching site from localhost.
The configuration that calls PHP-FPM is below. Let's call it main snippet.
location ~ \.php$ {
fastcgi_split_path_info ^(.+\.php)(/.+)$;
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
include fastcgi.conf;
}
If I use the following snippet after the main snippet (let's call it blocking snippet)
location ~ /(admin) {
allow 127.0.0.1;
deny all;
}
users that access /admin folder from 127.0.0.1. Users that access it from its public IP (say 192.168.0.71) have access denied. Great (but not that much). If they try to access any PHP file inside /admin folder, PHP code is executed but no other asset is accessed (for instance, /admin/index.php)
Then I moved the blocking snippet so it would sit above the main snippet.
In this case, if someone tries to access /admin folder or any content (even PHP code), he/she gets the error 403 (access denied). Great (but again, not that much).
If someone tries to access /admin folder from 127.0.0.1 access is granted but PHP code is not executed as it is handled by main snippet that is below the blocking snippet. Instead of get executed, the PHP code is downloaded.
Then I thought to use the following snippet
location ~ /(admin.*\.php) {
allow 127.0.0.1;
deny all;
}
below the main snippet. But it didn't worked either (probably because main snippet got executed)
So my question: How can I allow users to access /admin folder from IP 127.0.0.1 and deny access to it and all its content (including PHP execution) if accessed from another IP?
What is wrong in my approach? I googled but I failed to find a solution.
Edit: configuration after Gary suggestion
server {
listen 80 default_server;
listen [::]:80 default_server ipv6only=on;
root /var/www/html;
index index.php index.html index.htm;
server_name localhost;
location / {
try_files $uri $uri/ /index.php?$args =404;
}
location ~ /(admin\/?) {
allow 127.0.0.1;
deny all;
location ~ \.php$ {
fastcgi_split_path_info ^(.+\.php)(/.+)$;
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
include fastcgi.conf;
}
}
location ~ \.php$ {
# regex to split $uri to $fastcgi_script_name and $fastcgi_path
fastcgi_split_path_info ^(.+\.php)(/.+)$;
# With php7.0-fpm:
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
include fastcgi.conf;
}
}