How to Set Up HTTP Authentication on a CentOS 7 Cloud Server Using Nginx?

02-02-2024 02:20:49

To begin with, ensure that you have a CentOS 7 cloud server prepared, with Nginx installed. This guide will explain how to set up HTTP authentication for Nginx on this CentOS 7 cloud server.

First, install the 'http-tools' package.

yum install httpd-tools

Next, create a '.htpasswd' file and enter a password twice as prompted.

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

The '.htpasswd' file contains the username and password for accessing a specific directory, where '/path/to/directory' is the directory requiring HTTP authentication. At this point, the authorization file is successfully created. The next step is to configure Nginx to recognize this authorization file.

In Nginx's configuration file, add the last two lines, which involve the 'auth_basic' and 'auth_basic_user_file' directives.

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
    }

The 'auth_basic' directive specifies the prompt text displayed by the browser when accessing the directory, while the 'auth_basic_user_file' directive defines the path to the '.htpasswd' file.

Finally, restart the Nginx service to apply these changes.

/etc/init.d/nginx restart

To test, access the URL of the directory. A dialogue box should appear in the browser, prompting you to enter the username and password to gain access.