NGINX Tutorial for Beginners

NGINX is a free, open-source web server that is commonly used to serve websites, act as a reverse proxy, balance traffic across application servers, cache responses, and proxy TCP/UDP traffic. It is known for its event-driven architecture, which allows it to handle many concurrent connections efficiently.

This NGINX tutorial explains what NGINX does, where it fits in a web application stack, how its configuration files are organized, and how to set up common use cases such as a static website, a reverse proxy, and simple load balancing.

What NGINX Is Used For

NGINX can be used in different layers of a web infrastructure. In small projects, it may directly serve static files such as HTML, CSS, JavaScript, images, and downloads. In application deployments, it is often placed in front of Node.js, Python, PHP, Java, Ruby, or Go applications as a reverse proxy.

  • Web server: Serves static website files from a directory.
  • Reverse proxy: Receives client requests and forwards them to an application server running behind NGINX.
  • Load balancer: Distributes requests across multiple backend servers.
  • HTTP cache: Stores selected responses to reduce repeated backend work.
  • TLS termination point: Handles HTTPS certificates before forwarding traffic internally.
  • TCP/UDP proxy: Proxies non-HTTP network traffic when configured for stream processing.

Why Use NGINX in a Web Application Stack?

NGINX fits into existing infrastructure without requiring a complete redesign. For example, an application can continue running on its usual port, while NGINX listens on public ports 80 and 443 and forwards traffic to the application internally.

The main reasons to use NGINX are practical: it can serve static assets efficiently, keep slow client connections away from the application server, route traffic to different services, and provide a single place to manage HTTPS, redirects, compression, and access rules.

NGINX Event-Driven Connection Handling

Traditional threaded servers may create or allocate a separate thread or process for each connection. NGINX uses an event-driven model where worker processes handle many connections asynchronously. This design helps NGINX serve many simultaneous clients with comparatively low memory usage.

This does not mean NGINX automatically makes every website fast. Application code, database queries, network latency, caching strategy, image size, and server resources still matter. NGINX is useful because it gives you a reliable front layer for routing, serving, proxying, and controlling traffic.

Install NGINX on Ubuntu or Debian

On Ubuntu or Debian-based systems, NGINX can be installed from the package repository. The package name is usually nginx.

</>
Copy
sudo apt update
sudo apt install nginx
sudo systemctl enable nginx
sudo systemctl start nginx

After installation, check whether the service is running.

</>
Copy
systemctl status nginx

If a firewall is enabled, allow HTTP and HTTPS traffic as required by your server setup.

</>
Copy
sudo ufw allow 'Nginx Full'

NGINX Configuration File Structure

The main NGINX configuration file is commonly located at /etc/nginx/nginx.conf. On many Linux distributions, individual website configurations are placed in /etc/nginx/sites-available/ and enabled by symbolic links inside /etc/nginx/sites-enabled/.

Exact paths can vary by operating system and installation method, but the basic configuration idea remains the same: NGINX reads directives organized into blocks.

</>
Copy
events {
    worker_connections 1024;
}

http {
    server {
        listen 80;
        server_name example.com;

        location / {
            root /var/www/example;
            index index.html;
        }
    }
}

In this example, events contains connection-related settings, http contains HTTP server configuration, server defines a virtual server, and location defines how NGINX handles a matching request path.

Serve a Static Website with NGINX

To serve a basic static website, create a directory for the site files and add an index.html file.

</>
Copy
sudo mkdir -p /var/www/example.com
sudo nano /var/www/example.com/index.html

Add a simple test page.

</>
Copy
<!DOCTYPE html>
<html>
<head>
    <title>Example NGINX Site</title>
</head>
<body>
    <h1>NGINX is serving this page</h1>
</body>
</html>

Then create a server block for the website.

</>
Copy
server {
    listen 80;
    server_name example.com www.example.com;

    root /var/www/example.com;
    index index.html;

    location / {
        try_files $uri $uri/ =404;
    }
}

If you created this file in sites-available, enable it by linking it to sites-enabled.

</>
Copy
sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/example.com

Test and Reload NGINX Configuration

Always test the configuration before reloading NGINX. This helps catch syntax errors such as missing semicolons, incorrect braces, or invalid directive placement.

</>
Copy
sudo nginx -t

If the configuration test is successful, reload NGINX without stopping the service.

</>
Copy
sudo systemctl reload nginx

A reload applies configuration changes while keeping the service available. A restart stops and starts the service, which is usually not needed for normal configuration updates.

Configure NGINX as a Reverse Proxy

A reverse proxy receives requests from users and forwards them to an application running on another port or server. For example, a Node.js, Python, or Java application may run internally on port 3000, while NGINX listens publicly on port 80 or 443.

</>
Copy
server {
    listen 80;
    server_name app.example.com;

    location / {
        proxy_pass http://127.0.0.1:3000;
        proxy_http_version 1.1;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}

The proxy_pass directive forwards the request to the backend application. The proxy_set_header directives pass useful request information to the application, such as the original host, client IP address, and protocol.

Configure NGINX Load Balancing

NGINX can distribute traffic across multiple backend servers using an upstream block. This is useful when the same application runs on more than one server or port.

</>
Copy
upstream app_backend {
    server 127.0.0.1:3000;
    server 127.0.0.1:3001;
}

server {
    listen 80;
    server_name app.example.com;

    location / {
        proxy_pass http://app_backend;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}

By default, NGINX distributes requests using round-robin selection. For production environments, also review health checks, timeouts, upstream failure handling, application session behavior, and logging before relying on load balancing.

Important NGINX Directives for Beginners

DirectivePurposeCommon use
listenDefines the IP address and port for a server block.listen 80; for HTTP.
server_nameMatches the requested hostname.example.com and www.example.com.
rootSets the directory used to serve files.Static websites.
indexDefines default files for a directory.index.html or index.php.
locationMatches request paths and applies rules.Routing, proxying, redirects.
try_filesChecks files in order before returning a fallback.Static sites and front-controller apps.
proxy_passForwards requests to another server.Reverse proxy setup.

NGINX Logs for Debugging Requests

NGINX logs are important when a site is not loading as expected. On many Linux systems, access and error logs are stored under /var/log/nginx/.

</>
Copy
sudo tail -f /var/log/nginx/access.log
sudo tail -f /var/log/nginx/error.log

The access log shows requests received by NGINX. The error log shows configuration issues, file permission problems, upstream connection failures, and other runtime errors.

Common NGINX Errors and Fixes

ProblemLikely causeWhat to check
403 ForbiddenPermission issue or missing index file.Check directory permissions, file ownership, and index directive.
404 Not FoundWrong root, missing file, or incorrect location.Check file path and try_files behavior.
502 Bad GatewayBackend app is down or unreachable.Check proxy_pass, app port, firewall, and backend logs.
nginx: configuration file test failedSyntax or directive error.Run sudo nginx -t and read the reported line number.
Default NGINX page appearsWrong server block is active.Check server_name, enabled site files, and DNS.

Basic NGINX Security and Performance Settings

After the first setup works, review basic security and performance settings. These settings should be adjusted carefully according to your application, traffic, and hosting environment.

  • Use HTTPS for public websites and renew certificates before they expire.
  • Keep NGINX and the operating system updated through trusted package sources.
  • Disable unnecessary default sites if they are not used.
  • Set appropriate file and directory permissions for website files.
  • Use compression only for suitable text-based content.
  • Set request body size limits when uploads are allowed.
  • Review timeout values for reverse proxy and upstream applications.
  • Monitor access logs and error logs after deployment changes.

Useful NGINX Commands

CommandUse
sudo nginx -tTests the NGINX configuration.
sudo systemctl start nginxStarts the NGINX service.
sudo systemctl stop nginxStops the NGINX service.
sudo systemctl reload nginxReloads configuration without a full restart.
sudo systemctl restart nginxRestarts the service completely.
sudo systemctl status nginxShows current service status.
nginx -VDisplays version and compile-time options.

NGINX Official Documentation and Reference Links

For deeper configuration details, refer to the official NGINX documentation and the official NGINX beginner’s guide. For Ubuntu-specific installation steps, the Ubuntu NGINX installation tutorial is also useful.

NGINX Tutorial FAQs

What is NGINX used for?

NGINX is used as a web server, reverse proxy, load balancer, HTTP cache, TLS termination point, and TCP/UDP proxy. A common setup is to place NGINX in front of an application server and let it handle public HTTP or HTTPS traffic.

Is NGINX only for static websites?

No. NGINX can serve static files directly, but it is also widely used to proxy requests to dynamic applications such as Node.js, Python, PHP, Java, Ruby, and Go services.

What is the difference between NGINX reload and restart?

A reload applies configuration changes without fully stopping the NGINX service. A restart stops and starts the service. For normal configuration changes, test with nginx -t and then reload.

Why does NGINX show 502 Bad Gateway?

A 502 Bad Gateway error usually means NGINX could not reach the upstream application server. Check whether the backend application is running, whether the port in proxy_pass is correct, and whether firewall or permission rules are blocking the connection.

Where are NGINX configuration files stored?

The main file is commonly /etc/nginx/nginx.conf. On many Debian and Ubuntu installations, site-specific files are stored in /etc/nginx/sites-available/ and enabled through links in /etc/nginx/sites-enabled/. The exact structure may vary by operating system and package.

Editorial QA Checklist for This NGINX Tutorial

  • Verify that every NGINX configuration block has matching braces and semicolons.
  • Ensure new command examples use language-bash and output-only blocks use the output class.
  • Check that reverse proxy examples include the important forwarded headers.
  • Confirm that installation instructions do not assume the same file paths for every operating system.
  • Keep NGINX performance claims practical and avoid unsupported traffic or speed guarantees.
  • Review all official documentation links for relevance before publishing updates.