Learn How To Setup HTTP Authentication With Nginx on CentOS 7

March 16, 2019

Table of Contents

In this guide, you will learn how to setup HTTP authentication for an Nginx web server running on CentOS 7.


To get started, you’ll need the following things:

  • SSH Client (like PuTTY, Bitvise SSH, etc)
  • VPS Server with CentOS 7 x64 installed.
  • Nginx installed on the server.

Let’s get started

Install the httpd-tools package.

yum install httpd-tools

Create an .htpasswd file.

htpasswd -c /path/to/directory/.htpasswd username

The .htpasswd file will contain the information about username and password. /path/to/directory – is the full path to the directory for which we want to set-up authentication. username – we will use that for authentication – you can choose what ever you want. You will be asked to enter a password for the user. Enter a secure password and confirm it by re-entering the same password again.

We have successfully created the user for authentication, now the only thing left to do is to modify the Nginx configuration to use the .htpasswd file, which we have just created.

You will find your default configuration under /etc/nginx/conf.d/default.conf.

We are going to add 2 lines to the configuration.

server {
    listen       80;
    server_name  example.com www.example.com;
    location / {
        root /path/to/directory/;
        index index.php index.html index.htm;
        auth_basic "Restricted area - This system is for the use of authorized users only!";
        auth_basic_user_file /path/to/directory/.htpasswd

In particular, we’ve added these lines:

auth_basic "Restricted area - This system is for the use of authorized users only";
auth_basic_user_file /path/to/directory/.htpasswd

The first line defines the text showed in the login box when visiting the secured directory and the second line contains the path to our .htpasswd file.

Save the configuration and restart the Nginx service with /etc/init.d/nginx restart

Setup complete

Visit the secured directory on your website. You will see a login prompt that looks like this:

Type in your username and password and you’ll be granted access.

Need help?

Do you need help setting up this on your own service?
Please contact us and we’ll provide you the best possible quote!