I'm running 2 websites on a LEMP stack with nginx configured as a reverse proxy server. I have successfully installed phpmyadmin in the root folder of one of my sites root directories. When I go to www.example.com/phpmyadmin, I am able to access phpmyadmin login page on public internet as well as on my lan. What I would like to do is configure nginx to block any traffic to phpmyadmin that doesn't originate from my local area network. Currently I also have a /admin folder in the root of my site, and I HAVE SUCCESSFULLY set up a way to block all traffic to that folder that doesn't originate from my LAN. I figured blocking phpmyadmin from the outside world would be as easy using the same ngninx virtual configuration lines I used to block the /admin/ directory, but just changing the location to /phpmyadmin. However, when doing this, phpmyadmin is still blocked on the local network.
Below is the relevant parts of my nginx virtual host configuration for example.com. You can see what blocking configurations work and don't work as noted in the comments. Help me fix the #Not working lines. Note: My Server's local ip address is 192.168.1.20
.
server {
listen 443 ssl http2;
listen [::]:443 ssl http2;
ssl on;
ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
server_name example.com www.example.com;
root /var/www/example.com;
index index.php;
location / {
# try_files $uri $uri/ =404;
try_files $uri $uri/ /index.php?$args;
}
# Disallow PHP In Upload Folder
location /wp-content/uploads/ {
location ~ \.php$ {
deny all;
}
}
# LAN ONLY ACCESS WORKING
location ^~ /admin {
allow 192.168.1.0/24;
deny all;
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/var/run/php/php7.3-fpm.sock;
fastcgi_split_path_info ^(.+\.php)(/.+)$;
}
# LAN ONLY ACCESS NOT WORKING!!!
location ^~ /phpmyadmin {
allow 192.168.1.0/24;
deny all;
include fastcgi.conf;
fastcgi_intercept_errors on;
fastcgi_pass local_php;
fastcgi_buffers 16 16k;
fastcgi_buffer_size 32k;
}
location ~ \.php$ {
include fastcgi.conf;
fastcgi_intercept_errors on;
fastcgi_pass local_php;
fastcgi_buffers 16 16k;
fastcgi_buffer_size 32k;
}
}
What edits to my virtual host config file must I make to properly restrict phpmyadmin to my LAN in Nginx?
Try this one, works for me.
Unfortunately, @JRA's answer did not work. What did work was adding the restrict directives without using them as a location directive to the very top of the server blocks in the .conf file, like so...
Your issue is the order in which nginx applies location blocks. Specifically, the ~.php$ location is being processed before the ~/phpmyadmin block. Assuming that the phpmyadmin directory is in your webroot, using a literal prefix instead of a regex should give the behaviour you expect....
Although /admin is currently behaving as you expect, it would be a good idea to make that a literal prefix too.