Introduction

Welcome to the first lesson in our course on Securing Your NGINX Server! Security is a critical aspect of web server management, and in this lesson, we'll explore one of the most fundamental techniques: password protection using HTTP Basic Authentication.

By the end of this lesson, you'll know how to configure NGINX to require credentials before granting access to sensitive areas of your application. This is particularly useful for protecting administrative panels, internal tools, or any content that should only be accessible to authorized users.

Why Authentication Matters

Before diving into the technical implementation, let's consider why we need authentication in the first place. Modern web applications often have sections that contain sensitive information or powerful administrative controls. Without proper protection, anyone who discovers these URLs could access them.

Common scenarios include:

  • Administrative dashboards that allow content management
  • Internal reporting tools with business metrics
  • Configuration panels that modify server behavior
  • User management interfaces

HTTP Basic Authentication provides a straightforward way to add a protective layer, ensuring only users with valid credentials can proceed.

Understanding HTTP Basic Authentication

HTTP Basic Authentication is one of the simplest authentication mechanisms available. When a user attempts to access a protected resource, the server responds with a challenge. The browser then prompts the user for a username and password, which it sends back to the server encoded in base64.

While basic authentication isn't as sophisticated as modern OAuth or JWT-based systems, it serves as an excellent first line of defense. It's particularly effective for internal tools, development environments, or scenarios where you need quick, reliable protection without complex infrastructure.

The key advantage is its simplicity: it's built into the HTTP protocol itself and works across all browsers without requiring custom code or external services.

Setting Up the Server Foundation

Let's begin with the basic NGINX configuration that establishes our server context:

This configuration creates a simple server listening on port 3000. The root location returns a plain "OK" response, which will remain publicly accessible. Our goal is to add a protected section that requires authentication.

Introducing the Protected Location

Now we'll add a new location block specifically for our administrative area. However, there's an important caveat to understand about NGINX's execution order: the return directive is processed immediately, before authentication checks occur.

This means if we simply wrote:

NGINX would return the response without ever validating credentials. To work around this behavior, we need to use an indirection pattern with try_files and a named location:

The auth_basic directive defines the authentication realm "Restricted Area" that appears in the browser's login dialog. The try_files directive with an empty string "" will always fail to find a file, causing NGINX to fall back to the named location @admin_ok. Crucially, authentication is checked before try_files executes, ensuring credentials are validated first.

Specifying the Credentials File

The auth_basic_user_file directive points to the .htpasswd file containing usernames and hashed passwords:

NGINX reads this file to validate the credentials provided by users. The file path .htpasswd is relative to the NGINX configuration directory. This file is typically created using tools like the htpasswd utility, which properly hashes passwords to ensure they're stored securely.

Note: The browser itself creates the login dialog when it receives an authentication challenge from NGINX—no need for you to make any input fields in your HTML. This is a built-in feature of the HTTP protocol that all modern browsers support automatically.

Adding Custom Authentication Headers

We can enhance our configuration by adding custom headers that indicate the authentication method being used:

The add_header directive with the always parameter ensures our custom header is included in every response, regardless of status code. This can be useful for debugging, logging, or informing client applications about the authentication scheme in use.

The Complete Configuration

Here's how all the pieces fit together in our final configuration:

Notice how the configuration maintains two distinct behaviors: the root location remains open to everyone, while the /admin/ path is locked down. The named location pattern ensures authentication happens before any response is sent.

How Authentication Flow Works

When this configuration is active, here's what happens when someone attempts to access /admin/:

  1. NGINX receives the request and matches it to the /admin/ location block
  2. The auth_basic directive triggers an authentication challenge
  3. The browser displays a login dialog with the realm name "Restricted Area"
  4. The user enters credentials, which the browser sends to NGINX
  5. NGINX checks these credentials against the .htpasswd file
  6. If invalid, NGINX returns a 401 Unauthorized response
  7. If valid, NGINX proceeds to the try_files directive
  8. The empty string fails to match any file, triggering the fallback to @admin_ok
  9. The named location executes, returning "admin" with the X-Auth header

This pattern ensures authentication always happens before content is served, giving you reliable protection.

Conclusion and Next Steps

You've successfully configured HTTP Basic Authentication in NGINX to protect sensitive application areas. You learned how the auth_basic and auth_basic_user_file directives work together, and importantly, how to use the try_files pattern with named locations to ensure authentication is checked before responses are sent.

This fundamental security technique provides a solid foundation for protecting administrative interfaces, internal tools, and other restricted content. While basic authentication has limitations for public-facing applications, it remains an excellent choice for internal systems and development environments.

Now it's time to put this knowledge into practice! In the upcoming exercises, you'll implement these authentication patterns hands-on, reinforcing your understanding and building confidence in securing NGINX servers.

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal