Bird
Raised Fist0
Nginxdevops~5 mins

Basic authentication in Nginx - Commands & Configuration

Choose your learning style10 modes available
Introduction
Sometimes you want to protect a website or a part of it so only certain people can see it. Basic authentication is a simple way to ask users for a username and password before they can access the page.
When you want to protect a small admin page on your website without setting up a full login system
When you need a quick password check for a staging or testing site before sharing it
When you want to restrict access to certain files or folders on your web server
When you want to add a simple layer of security to your website without complex coding
When you want to control access to a private API endpoint
Config File - nginx.conf
nginx.conf
server {
    listen 80;
    server_name example.com;

    location /secure/ {
        auth_basic "Restricted Content";
        auth_basic_user_file /etc/nginx/.htpasswd;
    }
}

This configuration tells Nginx to listen on port 80 for the domain example.com.

The location /secure/ block protects the /secure/ path.

auth_basic sets the message shown in the login popup.

auth_basic_user_file points to the file with usernames and passwords.

Commands
Install the tool 'htpasswd' which helps create the password file for basic authentication.
Terminal
sudo apt-get update && sudo apt-get install apache2-utils -y
Expected OutputExpected
Reading package lists... Done Building dependency tree Reading state information... Done The following NEW packages will be installed: apache2-utils 0 upgraded, 1 newly installed, 0 to remove and 0 not upgraded. Need to get 123 kB of archives. After this operation, 456 kB of additional disk space will be used. Get:1 http://archive.ubuntu.com/ubuntu focal/main amd64 apache2-utils amd64 2.4.41-4ubuntu3.9 [123 kB] Fetched 123 kB in 1s (123 kB/s) Selecting previously unselected package apache2-utils. (Reading database ... 123456 files and directories currently installed.) Preparing to unpack .../apache2-utils_2.4.41-4ubuntu3.9_amd64.deb ... Unpacking apache2-utils (2.4.41-4ubuntu3.9) ... Setting up apache2-utils (2.4.41-4ubuntu3.9) ...
Create a new password file and add a user named 'user1'. You will be asked to enter and confirm the password.
Terminal
sudo htpasswd -c /etc/nginx/.htpasswd user1
Expected OutputExpected
New password: Re-type new password: Adding password for user user1
→
-c - Create a new password file, overwriting if it exists
Check if the Nginx configuration file is valid before restarting the server.
Terminal
sudo nginx -t
Expected OutputExpected
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok nginx: configuration file /etc/nginx/nginx.conf test is successful
Reload Nginx to apply the new configuration without stopping the server.
Terminal
sudo systemctl reload nginx
Expected OutputExpected
No output (command runs silently)
Test accessing the protected URL. It should ask for authentication and respond with 401 Unauthorized if no credentials are provided.
Terminal
curl -i http://example.com/secure/
Expected OutputExpected
HTTP/1.1 401 Unauthorized Server: nginx/1.18.0 Date: Thu, 01 Jan 1970 00:00:00 GMT Content-Type: text/html Content-Length: 178 WWW-Authenticate: Basic realm="Restricted Content" <html> <head><title>401 Authorization Required</title></head> <body bgcolor="white"> <center><h1>401 Authorization Required</h1></center> <hr><center>nginx/1.18.0</center> </body> </html>
Key Concept

If you remember nothing else from this pattern, remember: basic authentication protects web content by asking users for a username and password stored in a simple file.

Common Mistakes
Not creating the password file before enabling basic authentication in Nginx
Nginx will fail to start or the protected area will not work because it cannot find the user file.
Always create the .htpasswd file with at least one user before reloading Nginx.
Using the -c flag with htpasswd to add users after the file already exists
The -c flag overwrites the existing file, deleting all previous users.
Use htpasswd without -c to add additional users to the existing file.
Not testing Nginx configuration with 'nginx -t' before reloading
If there is a syntax error, Nginx reload will fail and the server may stop serving requests.
Always run 'sudo nginx -t' to check configuration syntax before reloading.
Summary
Install 'apache2-utils' to get the htpasswd tool for creating password files.
Create a .htpasswd file with usernames and passwords using 'htpasswd -c' for the first user.
Configure Nginx to protect a location with 'auth_basic' and point to the .htpasswd file.
Test the Nginx configuration with 'nginx -t' and reload Nginx to apply changes.
Verify protection by accessing the protected URL and checking for authentication prompt.

Practice

(1/5)
1. What is the main purpose of basic authentication in nginx?
easy
A. To speed up the website loading time
B. To encrypt all website traffic automatically
C. To require users to enter a username and password before accessing content
D. To block all users except the server admin

Solution

  1. Step 1: Understand basic authentication purpose

    Basic authentication prompts users for a username and password to restrict access.
  2. Step 2: Compare options

    Only To require users to enter a username and password before accessing content describes this login prompt function; others describe unrelated features.
  3. Final Answer:

    To require users to enter a username and password before accessing content -> Option C
  4. Quick Check:

    Basic authentication = login prompt [OK]
Hint: Basic auth means login prompt for access control [OK]
Common Mistakes:
  • Confusing basic auth with encryption
  • Thinking it speeds up the site
  • Assuming it blocks all users except admin
2. Which nginx directive is used to enable basic authentication in a server block?
easy
A. auth_basic_user_file
B. auth_user_file
C. basic_auth_enable
D. auth_basic

Solution

  1. Step 1: Identify the directive for enabling basic auth

    The directive auth_basic enables basic authentication and sets the login prompt message.
  2. Step 2: Check other directives

    auth_basic_user_file is incorrect; the correct directive for the password file is auth_basic_user_file but the enabling directive is auth_basic.
  3. Final Answer:

    auth_basic -> Option D
  4. Quick Check:

    Enable basic auth = auth_basic [OK]
Hint: Enable basic auth with auth_basic directive [OK]
Common Mistakes:
  • Using auth_basic_user_file to enable auth
  • Confusing directive names
  • Using non-existent directives
3. Given this nginx config snippet:
location /secure/ {
  auth_basic "Restricted Area";
  auth_basic_user_file /etc/nginx/.htpasswd;
}

What happens when a user tries to access /secure/?
medium
A. User is prompted for username and password
B. User is redirected to /etc/nginx/.htpasswd
C. User accesses content without any prompt
D. User gets a 404 Not Found error

Solution

  1. Step 1: Analyze auth_basic directive

    The auth_basic directive enables a login prompt with the message "Restricted Area".
  2. Step 2: Analyze auth_basic_user_file directive

    The auth_basic_user_file points to the password file used to verify credentials.
  3. Step 3: Determine user experience

    When accessing /secure/, the user is asked for username and password to proceed.
  4. Final Answer:

    User is prompted for username and password -> Option A
  5. Quick Check:

    auth_basic + user_file = login prompt [OK]
Hint: auth_basic triggers login prompt on matching location [OK]
Common Mistakes:
  • Thinking user is redirected to password file
  • Assuming no prompt appears
  • Expecting 404 error without reason
4. You configured basic authentication but users are not prompted for credentials. Which is the most likely error?
medium
A. Missing auth_basic directive in the location block
B. Password file has wrong permissions
C. Using HTTP instead of HTTPS
D. Incorrect server_name directive

Solution

  1. Step 1: Check required directives for basic auth

    Both auth_basic and auth_basic_user_file are needed; missing auth_basic disables the prompt.
  2. Step 2: Evaluate other options

    Wrong permissions cause errors but usually show 500 errors; HTTP vs HTTPS affects security but not prompt; server_name unrelated.
  3. Final Answer:

    Missing auth_basic directive in the location block -> Option A
  4. Quick Check:

    No auth_basic = no login prompt [OK]
Hint: Always include auth_basic to enable prompt [OK]
Common Mistakes:
  • Ignoring missing auth_basic directive
  • Blaming HTTPS for prompt absence
  • Confusing server_name with auth settings
5. You want to protect only the /admin path with basic authentication but allow /admin/public without login. Which nginx config achieves this?
hard
A. Use location /admin/public/ { auth_basic "Admin Area"; } and location /admin/ { auth_basic off; }
B. Use location /admin/ { auth_basic "Admin Area"; auth_basic_user_file /etc/nginx/.htpasswd; } and location /admin/public/ { auth_basic off; }
C. Use location /admin/ { auth_basic off; } only
D. Use location /admin/public/ { auth_basic_user_file /etc/nginx/.htpasswd; } only

Solution

  1. Step 1: Protect /admin path with basic auth

    Set auth_basic and auth_basic_user_file in location /admin/ to require login.
  2. Step 2: Disable auth for /admin/public

    Override with auth_basic off; in location /admin/public/ to allow open access.
  3. Step 3: Confirm correct order and specificity

    More specific location /admin/public/ disables auth, while parent /admin/ requires it.
  4. Final Answer:

    Use location /admin/ with auth_basic and location /admin/public/ with auth_basic off -> Option B
  5. Quick Check:

    Parent location auth + child location off = selective protection [OK]
Hint: Disable auth in child location with auth_basic off [OK]
Common Mistakes:
  • Reversing auth_basic on/off in locations
  • Not using auth_basic off to disable
  • Only configuring one location
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard