Photo by Markus Spiske on Unsplash
Secure Your NGINX Server: A Step-by-Step Guide to Setting Up Basic Authentication
NGINX, a popular and powerful web server, offers various mechanisms to enhance security, one of which is Basic Authentication. This authentication method provides a straightforward yet effective way to control access to your server and restrict it to authorized users.
In this article, we'll guide you through the process of setting up Basic Authentication for your NGINX server, ensuring that only users with valid credentials can access your resources. Let's dive into the fundamentals and master the art of securing your NGINX server with Basic Authentication.
Imagine you're managing a web development project with multiple team members working on different aspects of the application. Your project has distinct environments, including staging and integration servers, where new features are tested before deployment.
These environments contain sensitive data, early-stage code, and crucial configurations for the development and testing phases. However, they shouldn't be freely accessible to anyone without proper authorization.
Basic Authentication becomes essential in this scenario, acting as a virtual security guard by requiring valid credentials before granting access. This precaution helps ensure that only authorized team members can view and interact with the staging and integration environments, safeguarding the integrity and confidentiality of your project's crucial stages.
Let's see how to enable this vital layer of security for your NGINX server effectively.
Enabling HTTP Basic Auth in NGINX.
NGINX provides two directives for enabling Basic Auth: auth_base
and auth_basic_user_file
Here is a sample NGINX configuration file
server {
listen 80 default_server;
server_name example.org;
location / {
auth_basic "Basic Auth Protected Site";
auth_basic_user_file /etc/conf.d/passwd;
proxy_pass http://localhost:8000/;
}
}
The auth_basic
directive takes a string parameter, which is displayed on the basic authentication pop-up window when an unauthenticated user arrives.
The auth_basic_user_file
is the path to the file containing user information - username and password.
auth_basic_user_file
As mentioned earlier, this file contains user information. It has the below format.
# This is a comment
username:hashed_password
The username is the first field, the password is the second field with a colon delimiter.
How do you generate the hashed password?
The openssl
command can come in handy here. Type this in your terminal.
$ openssl passwd mypassword
Use the output of this in your user file.
Reload your NGINX configuration with nginx -s reload
You can use curl
to make authenticated requests to your service
curl --user user:password https://example.org
If users visit the URL in your browser, they will be greeted with an alert asking for a username and password.
Make sure to serve your request over SSL.
It is as simple as that :)