To configure authentication for a website or a directory of it in NGINX, you can use the Apache htpasswd utility to store user passwords. This article will explain how to do it using the "ngx_http_auth_basic_module" module in NGINX and the "auth_basic" and "auth_basic_user_file" directives. You can find more information in the official NGINX documentation by clicking here.
How to Install htpasswd
First, you will need to install the Apache utility package that includes htpasswd:
# apt install apache2-utils -y
How to Use htpasswd to Add Credentials
# htpasswd -c /etc/nginx/.htpasswd example_user
# htpasswd /etc/nginx/.htpasswd example_user_two
How to Configure Authentication on an NGINX Site
auth_basic "Restricted Access";
auth_basic_user_file /etc/nginx/.htpasswd;
Once the "auth_basic" and "auth_basic_user_file" directives have been added to the NGINX configuration file, save the file and reload the configuration for the changes to take effect. You can do this by running the following command:
# nginx -s reload
Keep in mind that you will need to use sudo if you are not using the root user to run this command and reload the NGINX configuration. After this, you should be able to access your website protected by authentication. When you try to access the page, you will be prompted to enter a valid username and password from the htpasswd file.
How to Protect the htpasswd File
It is important to remember that the htpasswd file contains sensitive information, such as the usernames and passwords of your users. Therefore, you must ensure that it is properly protected. One way to do this is by restricting access to the file through user and group permissions on Linux. For example, you can run the following command in a terminal window to restrict access to the htpasswd file to only the "root" user and the "www-data" group:
# chown root:www-data /etc/nginx/.htpasswd
You can also run the following command to restrict read and write access to the htpasswd file to only the "root" user:
# chmod 640 /etc/nginx/.htpasswd
With these permission changes, only the "root" user and the "www-data" group will be able to read and write to the htpasswd file, which protects it from potential attacks. However, it is important to remember that this is just an example, and you should adjust the permissions according to your security needs and requirements.
Remember, if you have any questions about this or any other issue related to your servers on Clouding, do not hesitate to write to suport@clouding.io We are here to help you with whatever you need, feel free to ask us!