Nginx Web Server

Level: Intermediate Module: Web Services 8 min read Lesson 23 of 66

Overview

  • What you’ll learn: How to install Nginx on Ubuntu, understand its event-driven architecture, configure server blocks, serve static content, manage logs, and optimize performance.
  • Prerequisites: Lesson 22 — Apache2 Web Server
  • Estimated reading time: 18 minutes

Introduction

Nginx (pronounced “engine-x”) is a high-performance HTTP server, reverse proxy, and load balancer created by Igor Sysoev in 2004. Originally designed to solve the C10K problem — handling 10,000 concurrent connections — Nginx uses an asynchronous, event-driven architecture that consumes significantly less memory per connection compared to traditional process-based servers like Apache.

Today, Nginx is the most popular web server in the world by market share. It excels at serving static content, acting as a reverse proxy in front of application servers, and handling SSL/TLS termination. Many production deployments use Nginx as a front-end proxy with application backends running Node.js, Python, PHP-FPM, or other frameworks.

In this lesson, you will learn how to install and configure Nginx on Ubuntu, understand its configuration file structure, set up server blocks (the Nginx equivalent of Apache virtual hosts), serve static files, manage logging, and apply performance optimizations.

Nginx vs Apache Architecture

Understanding the architectural differences between Nginx and Apache helps you choose the right server for your use case:

  • Apache (mpm_event/prefork): Creates worker processes or threads for each connection. Flexible with .htaccess and dynamic module loading, but uses more memory under heavy load.
  • Nginx: Uses a single master process with multiple worker processes. Each worker handles thousands of connections using an event loop (epoll on Linux). No .htaccess equivalent — all configuration is centralized.

Nginx is generally preferred for high-concurrency static content serving and reverse proxying, while Apache’s .htaccess support and per-directory configuration make it convenient for shared hosting environments.

Installing Nginx

# Install Nginx from Ubuntu repositories
$ sudo apt update
$ sudo apt install nginx

# Verify installation
$ nginx -v
nginx version: nginx/1.18.0 (Ubuntu)

# Check service status
$ sudo systemctl status nginx
● nginx.service - A high performance web server and a reverse proxy server
     Active: active (running)

# Test default page
$ curl -I http://localhost/
HTTP/1.1 200 OK
Server: nginx/1.18.0 (Ubuntu)

If Apache is already running on port 80, you must stop it before starting Nginx:

$ sudo systemctl stop apache2
$ sudo systemctl disable apache2
$ sudo systemctl start nginx

Configuration File Structure

Nginx configuration on Ubuntu follows this layout:

/etc/nginx/
├── nginx.conf              # Main configuration file
├── mime.types              # MIME type mappings
├── conf.d/                 # Additional configuration files
├── sites-available/        # Available server block definitions
├── sites-enabled/          # Enabled server blocks (symlinks)
├── snippets/               # Reusable configuration snippets
└── modules-enabled/        # Enabled dynamic modules

Main Configuration — nginx.conf

The main configuration file defines global settings, the events context, and the HTTP context:

# /etc/nginx/nginx.conf
user www-data;
worker_processes auto;
pid /run/nginx.pid;
include /etc/nginx/modules-enabled/*.conf;

events {
    worker_connections 768;
    # multi_accept on;
}

http {
    sendfile on;
    tcp_nopush on;
    types_hash_max_size 2048;

    include /etc/nginx/mime.types;
    default_type application/octet-stream;

    access_log /var/log/nginx/access.log;
    error_log /var/log/nginx/error.log;

    gzip on;

    include /etc/nginx/conf.d/*.conf;
    include /etc/nginx/sites-enabled/*;
}

Key directives:

  • worker_processes auto: Automatically sets one worker per CPU core.
  • worker_connections: Maximum simultaneous connections per worker process.
  • sendfile: Enables efficient file transfer using the kernel’s sendfile() system call.
  • gzip: Enables response compression.

Server Blocks

Server blocks are the Nginx equivalent of Apache virtual hosts. They define how Nginx handles requests for different domains:

# Create document root
$ sudo mkdir -p /var/www/example.com/html
$ echo "<h1>Welcome to example.com on Nginx</h1>" | sudo tee /var/www/example.com/html/index.html
$ sudo chown -R www-data:www-data /var/www/example.com

# Create server block configuration
$ sudo nano /etc/nginx/sites-available/example.com
# /etc/nginx/sites-available/example.com
server {
    listen 80;
    listen [::]:80;

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

    access_log /var/log/nginx/example.com.access.log;
    error_log /var/log/nginx/example.com.error.log;

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

    location /images/ {
        expires 30d;
        add_header Cache-Control "public, immutable";
    }

    location ~* .(css|js|jpg|png|gif|ico|woff2)$ {
        expires 7d;
        add_header Cache-Control "public";
    }
}
# Enable the server block by creating a symlink
$ sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/

# Remove default site (optional)
$ sudo rm /etc/nginx/sites-enabled/default

# Test configuration syntax
$ sudo nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

# Reload Nginx
$ sudo systemctl reload nginx

Location Blocks and Request Processing

Nginx uses location blocks to match request URIs and apply specific configuration. Location matching follows a priority order:

  • Exact match (=): location = /favicon.ico { ... } — highest priority.
  • Preferential prefix (^~): location ^~ /static/ { ... } — stops regex search if matched.
  • Regex (~ or ~*): location ~* .(jpg|png)$ { ... } — case-sensitive or case-insensitive.
  • Prefix match: location /api/ { ... } — longest prefix wins if no regex matches.
server {
    # Exact match — highest priority
    location = /health {
        return 200 "OKn";
        add_header Content-Type text/plain;
    }

    # Prefix match — stops regex search
    location ^~ /static/ {
        root /var/www/assets;
        expires 30d;
    }

    # Regex match — case insensitive
    location ~* .(css|js)$ {
        expires 7d;
    }

    # Default prefix match
    location / {
        try_files $uri $uri/ =404;
    }
}

Performance Optimization

# /etc/nginx/nginx.conf — optimized settings
worker_processes auto;

events {
    worker_connections 4096;
    multi_accept on;
    use epoll;
}

http {
    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;
    keepalive_requests 100;

    # Gzip compression
    gzip on;
    gzip_vary on;
    gzip_proxied any;
    gzip_comp_level 6;
    gzip_min_length 256;
    gzip_types text/plain text/css application/json
               application/javascript text/xml application/xml
               application/xml+rss text/javascript;

    # Buffer sizes
    client_body_buffer_size 16k;
    client_max_body_size 50m;
    large_client_header_buffers 4 16k;

    # Open file cache
    open_file_cache max=10000 inactive=30s;
    open_file_cache_valid 60s;
    open_file_cache_min_uses 2;
}

Logging and Monitoring

# View access log
$ sudo tail -f /var/log/nginx/access.log

# View error log
$ sudo tail -f /var/log/nginx/error.log

# Custom log format
log_format detailed '$remote_addr - $remote_user [$time_local] '
                    '"$request" $status $body_bytes_sent '
                    '"$http_referer" "$http_user_agent" '
                    '$request_time $upstream_response_time';

access_log /var/log/nginx/access.log detailed;

# Check active connections (requires stub_status module)
# Add to a server block:
location /nginx_status {
    stub_status;
    allow 127.0.0.1;
    deny all;
}

$ curl http://localhost/nginx_status
Active connections: 3
server accepts handled requests
 1542 1542 3847
Reading: 0 Writing: 1 Waiting: 2

Key Takeaways

  • Nginx uses an event-driven, non-blocking architecture that efficiently handles thousands of concurrent connections with minimal memory.
  • Install Nginx with sudo apt install nginx; it listens on port 80 by default.
  • Server blocks (in /etc/nginx/sites-available/) are the Nginx equivalent of Apache virtual hosts.
  • Use sudo nginx -t to validate configuration before reloading with sudo systemctl reload nginx.
  • Location blocks match request URIs with a defined priority: exact, preferential prefix, regex, then prefix.
  • The try_files directive is essential for routing — it checks file existence before returning a 404 or forwarding to an application.
  • Enable gzip compression, tune worker processes and connections, and use open file caching for optimal performance.

What’s Next

In Lesson 24, you will learn how to secure your web servers with TLS certificates and HTTPS. You will use Let’s Encrypt and Certbot to obtain free certificates and configure both Apache and Nginx for encrypted connections.

繁體中文

概述

  • 您將學到: 如何在 Ubuntu 上安裝 Nginx、理解其事件驅動架構、設定伺服器區塊、提供靜態內容、管理日誌和優化效能。
  • 先決條件: 第 22 課 — Apache2 網頁伺服器
  • 預估閱讀時間: 18 分鐘

簡介

Nginx(讀作 “engine-x”)是由 Igor Sysoev 於 2004 年建立的高效能 HTTP 伺服器、反向代理和負載均衡器。Nginx 使用非同步、事件驅動的架構,與傳統的基於程序的伺服器相比,每個連線消耗的記憶體顯著更少。

今天,Nginx 是按市場份額計算世界上最受歡迎的網頁伺服器。它擅長提供靜態內容、作為應用伺服器前的反向代理,以及處理 SSL/TLS 終止。

Nginx 與 Apache 架構比較

  • Apache: 為每個連線建立工作程序或執行緒。支援 .htaccess 和動態模組載入,但在高負載下使用更多記憶體。
  • Nginx: 使用單一主程序和多個工作程序,每個工作程序使用事件迴圈處理數千個連線。沒有 .htaccess 等效功能。

安裝 Nginx

$ sudo apt update
$ sudo apt install nginx
$ nginx -v
$ sudo systemctl status nginx

設定檔結構

/etc/nginx/
├── nginx.conf              # 主設定檔
├── sites-available/        # 可用的伺服器區塊定義
├── sites-enabled/          # 已啟用的伺服器區塊(符號連結)
└── snippets/               # 可重複使用的設定片段

伺服器區塊

伺服器區塊是 Nginx 等同於 Apache 虛擬主機的功能。

server {
    listen 80;
    server_name example.com www.example.com;
    root /var/www/example.com/html;
    index index.html;

    location / {
        try_files $uri $uri/ =404;
    }
}
# 建立符號連結啟用伺服器區塊
$ sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/

# 測試設定語法
$ sudo nginx -t

# 重新載入 Nginx
$ sudo systemctl reload nginx

位置區塊和請求處理

  • 精確匹配(=): 最高優先級。
  • 優先前綴(^~): 如果匹配則停止正規表達式搜索。
  • 正規表達式(~~*): 區分大小寫或不區分。
  • 前綴匹配: 最長前綴獲勝。

效能優化

worker_processes auto;
events {
    worker_connections 4096;
    multi_accept on;
    use epoll;
}
http {
    sendfile on;
    tcp_nopush on;
    gzip on;
    gzip_comp_level 6;
    gzip_types text/plain text/css application/json application/javascript;
}

重點整理

  • Nginx 使用事件驅動、非阻塞架構,以最少記憶體高效處理數千個併發連線。
  • 使用 sudo apt install nginx 安裝;預設監聽 80 埠。
  • 伺服器區塊是 Nginx 等同於 Apache 虛擬主機的功能。
  • 使用 sudo nginx -t 驗證設定,然後使用 sudo systemctl reload nginx 重新載入。
  • 啟用 gzip 壓縮、調整工作程序和連線數以獲得最佳效能。

下一步

在第 24 課中,您將學習如何使用 TLS 憑證和 HTTPS 保護網頁伺服器。

日本語

概要

  • 学習内容: Ubuntu での Nginx のインストール、イベント駆動アーキテクチャの理解、サーバーブロック設定、静的コンテンツ配信、ログ管理、パフォーマンス最適化。
  • 前提条件: レッスン 22 — Apache2 ウェブサーバー
  • 推定読了時間: 18 分

はじめに

Nginx(”engine-x” と発音)は、2004 年に Igor Sysoev が作成した高性能 HTTP サーバー、リバースプロキシ、ロードバランサーです。非同期のイベント駆動アーキテクチャを使用し、従来のプロセスベースのサーバーと比較して接続あたりのメモリ消費が大幅に少なくなっています。

Nginx と Apache のアーキテクチャ比較

  • Apache: 各接続にワーカープロセスまたはスレッドを作成。.htaccess と動的モジュールロードをサポートするが、高負荷時はメモリ使用量が増加。
  • Nginx: 単一のマスタープロセスと複数のワーカープロセスを使用。各ワーカーはイベントループで数千の接続を処理。

Nginx のインストール

$ sudo apt update
$ sudo apt install nginx
$ nginx -v
$ sudo systemctl status nginx

設定ファイル構造

/etc/nginx/
├── nginx.conf              # メイン設定ファイル
├── sites-available/        # 利用可能なサーバーブロック定義
├── sites-enabled/          # 有効なサーバーブロック(シンボリックリンク)
└── snippets/               # 再利用可能な設定スニペット

サーバーブロック

サーバーブロックは Apache のバーチャルホストに相当する Nginx の機能です。

server {
    listen 80;
    server_name example.com www.example.com;
    root /var/www/example.com/html;
    index index.html;

    location / {
        try_files $uri $uri/ =404;
    }
}
# シンボリックリンクでサーバーブロックを有効化
$ sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/

# 設定構文をテスト
$ sudo nginx -t

# Nginx をリロード
$ sudo systemctl reload nginx

ロケーションブロックとリクエスト処理

  • 完全一致(=): 最高優先度。
  • 優先プレフィックス(^~): マッチした場合、正規表現検索を停止。
  • 正規表現(~ または ~*): 大文字小文字区別ありまたはなし。
  • プレフィックスマッチ: 最長プレフィックスが優先。

パフォーマンス最適化

worker_processes auto;
events {
    worker_connections 4096;
    multi_accept on;
    use epoll;
}
http {
    sendfile on;
    tcp_nopush on;
    gzip on;
    gzip_comp_level 6;
}

重要ポイント

  • Nginx はイベント駆動の非ブロッキングアーキテクチャを使用し、最小限のメモリで数千の同時接続を効率的に処理。
  • sudo apt install nginx でインストール、デフォルトでポート 80 でリッスン。
  • サーバーブロックは Apache のバーチャルホストに相当。
  • sudo nginx -t で設定を検証し、sudo systemctl reload nginx でリロード。
  • gzip 圧縮の有効化、ワーカー数と接続数の調整で最適なパフォーマンスを実現。

次のステップ

レッスン 24 では、TLS 証明書と HTTPS でウェブサーバーを保護する方法を学びます。

You Missed