NGINX – Basic HTTP Authentication
Wanting to add a little security to your site? It’s actually incredibly easy…

This applies to Ubuntu 18 and 20; I’m sure it’s similar on CentOS as well.
Assuming you’ve already built a site that runs on NGINX; there’s one dependency in order to generate the user config.
sudo apt install apache2-utils #is all, you may need to create the /etc/apache2/ directory as well.
Once you’ve got the utilities installed and the apache2 directory in place, the below command will create a user named “user” – you will be prompted to enter the user’s password after running:
sudo htpasswd -c /etc/apache2/.htpasswd user
The -c flag is only needed if the file doesn’t exist, if you use it again, it will overwrite the file and you’ll lose existing users.
Now to enable the function for your site-
Add the following to the server you’d like to secure, I always put it right above the location directive.
auth_basic “Authentication required”;
auth_basic_user_file /etc/apache2/.htpasswd;
Save the site configuration and check nginx config with nginx -t
-If no errors are returned, restart nginx and there you have it,
basic http auth for your website.
-You don’t have to put the user file in /etc/apache2, you can add it wherever you’d like, just make sure your config matches.
Thanks for reading.
Joe-
Leave a Reply