How to Password Protect Apache and Nginx with Basic Authentication

Basic auth on Apache and Nginx

Hey there! Some links on this page may be affiliate links which means that, if you choose to make a purchase, I may earn a small commission at no extra cost to you. I greatly appreciate your support!

In this tutorial, you will learn how to implement HTTP basic authentication on both Apache and Nginx web servers. Basic authentication will allow you to password protect your entire website or just a subdirectory.

1. Generate a Password with htpasswd

Regardless of what type of web server you are running, you will need to first create a username and generate a password. We can do this the the htpasswd command.

If you are using Apache, you probably already have htpasswd installed. Nginx users will need to install this package with the apt package manager as follows.

apt install apache2-utils

Now you can create a username and password. If you are on Apache, swap out nginx in the command below with apache2.

htpasswd -c /etc/nginx/.htpasswd tony

This will create a user named tony and prompt you to type a password. Feel free to create multiple users this way if necessary.

2. Implement Basic Authentication

With your credentials in place, you can password protect a directory of your website or your entire website if you desire.

Apache Basic Auth Example

To implement basic authentication on Apache, add the following block to your website’s configuration file.

<Directory "/var/www/html/admin">
        AuthType Basic
        AuthName "admin area"
        AuthUserFile /etc/apache2/.htpasswd
        Require valid-user
</Directory>

Notice how we use AuthType Basic and point the AuthUserFile to the htpasswd database that you created in step one to password protect the /admin subdirectory of your website.

Apply this change by restarting Apache.

systemctl restart apache2

YouTube video

Nginx Basic Auth Example

To implement basic authentication on Nginx, add the following block to your website’s configuration file within the server block.

location /admin {
        try_files $uri $uri/ =404;
        auth_basic "admin area";
        auth_basic_user_file /etc/nginx/.htpasswd;
}

Notice how we use auth_basic and point the auth_basic_user_file to the htpasswd database that you created in step one to password protect the /admin subdirectory of your website.

Apply this change by restarting Nginx.

systemctl restart nginx

YouTube video

Facebook
Twitter
Pinterest
LinkedIn
Reddit

Meet Tony

Tony from Tony Teaches Tech headshot

With a strong software engineering background, Tony is determined to demystify the web. Discover why Tony quit his job to pursue this mission. You can join the Tony Teaches Tech community here.

Leave a Reply

Your email address will not be published. Required fields are marked *