Password Protecting Pages with NGINX
9 May 2023
I wanted to create some pages for my family to access anywhere. Putting them on this server seemed like a good option since I'm already paying the hosting fees. nginx provides some features to help restrict access to my family and friends. I decided to create a directory on the server that will be password protected where I can throw everything sensitive.
In the nginx config file, within the server block, I created a new location directive. There should be a couple others already there if you're not sure where it goes.
location /private/ { auth_basic "Please enter your credentials"; auth_basic_user_file path/to/.htpasswd; }
This puts a password on everything within the akbatten.com/private/ directory. The user file is a file that contains the accepted usernames and a hash of their password. This can be created with the htpasswd command:
sudo htpasswd -c /etc/nginx/.htpasswd user1
The .htpasswd file can go wherever you want, and can be named anything you want. For additional users, omit the -c flag.
To properly serve a php file/page, we need to add another location directive. Requests can only match 1 location directive. If it's caught by the new password one, a browser will download it with all php code included as you typed it. If the default php block catches it, it will be served without asking for a password.
I used some regex to catch password protected php requests and copied the code from both the password and php blocks:
location ~ private/.*\.php { auth_basic "Please enter your credentials"; auth_basic_user_file path/to/.htpasswd; include snippets/fastcgi-php.conf; fastcgi_pass unix:/var/run/php/php7.2-fpm.sock; }
Save the changes and be sure to test and reload the nginx config:
sudo nginx -t sudo nginx -s reload