Nginx vs Apache trên VPS Linux: Cấu hình thực tế và khi nào dùng cái nào

Câu hỏi "Nginx hay Apache?" xuất hiện trong hầu hết mọi cuộc thảo luận về web server. Câu trả lời ngắn: Nginx cho hầu hết use case hiện đại, Apache khi bạn cần per-directory config hoặc đang chạy legacy PHP app phụ thuộc vào .htaccess. Bài này giải thích tại sao và cách cấu hình từng loại cho từng tình huống cụ thể.

Kiến trúc — nguồn gốc của sự khác biệt

Apache — Process-based (Prefork/Worker/Event MPM)

Apache truyền thống dùng mô hình prefork: mỗi request được xử lý bởi một process riêng. Khi có 500 concurrent connections, Apache cần spawn 500 processes (hoặc threads với Worker MPM). Mỗi process chiếm ~5–20MB RAM tùy cấu hình và module được load.

Từ Apache 2.4 có thêm Event MPM — cải thiện đáng kể khả năng xử lý keep-alive connections mà không tốn một thread/process mỗi connection nhàn rỗi. Tuy nhiên vẫn không match được hiệu quả bộ nhớ của Nginx ở mức tải cao.

Nginx — Event-driven, non-blocking

Nginx dùng kiến trúc event-driven với một master process và một số worker processes (thường bằng số CPU cores). Mỗi worker xử lý hàng nghìn connections đồng thời qua non-blocking I/O và epoll/kqueue. Kết quả: Nginx có thể handle 10.000+ concurrent connections với memory footprint chỉ vài chục MB.

Về benchmark: Các benchmark "Nginx nhanh hơn 10x" thường đo trong điều kiện 10.000 concurrent static file requests — không phản ánh production thực tế. Với PHP application, bottleneck thường là PHP-FPM hoặc database, không phải web server. Sự khác biệt rõ nhất khi: static file serving ở scale lớn, và memory usage ở số lượng concurrent connections cao.

So sánh trực tiếp

Tiêu chíNginxApache
Kiến trúcEvent-driven, asyncProcess/thread per connection
Memory (idle, 100 connections)~5–15MB~50–200MB (prefork)
Static file throughputRất caoTốt, thấp hơn Nginx
PHP executionQua FastCGI (PHP-FPM)mod_php (tích hợp trực tiếp)
Per-directory configKhông (.htaccess không có)Có (.htaccess)
Reverse proxyRất mạnh, built-inCó, qua mod_proxy
Config syntaxBlock-based, súc tíchDirective-based, quen thuộc hơn
Tài liệu, cộng đồngTốtLâu đời, rất nhiều tài liệu

Cấu hình Nginx thực tế

Static file server tối ưu

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

    # Gzip compression
    gzip on;
    gzip_types text/plain text/css application/javascript image/svg+xml;
    gzip_min_length 1000;

    # Cache headers cho static assets
    location ~* \.(css|js|png|jpg|webp|woff2)$ {
        expires 1y;
        add_header Cache-Control "public, immutable";
        access_log off;
    }

    # sendfile để kernel xử lý file transfer trực tiếp
    sendfile on;
    tcp_nopush on;
}

PHP app với PHP-FPM

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

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    location ~ \.php$ {
        fastcgi_pass unix:/run/php/php8.2-fpm.sock;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
        fastcgi_read_timeout 60;
    }

    # Chặn truy cập file ẩn
    location ~ /\. { deny all; }
}

Reverse proxy cho Node.js / Python app

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

    location / {
        proxy_pass http://127.0.0.1:3000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        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_cache_bypass $http_upgrade;
        proxy_read_timeout 60s;
    }
}

Cấu hình Apache thực tế

VirtualHost cơ bản với .htaccess

<VirtualHost *:80>
    ServerName app.example.com
    DocumentRoot /var/www/app

    <Directory /var/www/app>
        Options -Indexes +FollowSymLinks
        AllowOverride All
        Require all granted
    </Directory>

    # Bật mod_rewrite cho .htaccess
    # (đảm bảo a2enmod rewrite đã chạy)
</VirtualHost>

File .htaccess cho Laravel/WordPress

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /

    # Bỏ qua file và thư mục thực sự tồn tại
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d

    # Redirect tất cả về index.php
    RewriteRule ^ index.php [L]
</IfModule>

# Nén response
<IfModule mod_deflate.c>
    AddOutputFilterByType DEFLATE text/html text/css application/javascript
</IfModule>

Khi nào dùng cái nào?

Chọn Nginx khi:

  • VPS RAM thấp (1–2GB) cần xử lý nhiều concurrent connections
  • Serve static files, assets, CDN origin
  • Reverse proxy cho Node.js, Python (FastAPI, Django), Go, hoặc bất kỳ app nào chạy port riêng
  • SSL termination cho nhiều domain
  • Bạn kiểm soát toàn bộ cấu hình server (không cần .htaccess)

Chọn Apache khi:

  • Chạy shared hosting environment nơi users cần tự cấu hình qua .htaccess
  • Legacy PHP app phụ thuộc vào mod_rewrite hoặc các Apache directives cụ thể
  • Dùng mod_php (tích hợp PHP trực tiếp vào Apache process — ít setup hơn PHP-FPM)
  • Team đã quen với Apache config và không có lý do kỹ thuật bắt buộc phải đổi

Dùng cả hai (Nginx + Apache):

Một pattern phổ biến: Nginx ở phía trước làm reverse proxy, Apache phía sau xử lý PHP với .htaccess. Nginx hứng toàn bộ traffic, serve static files trực tiếp, forward PHP requests sang Apache trên port nội bộ (thường 8080). Cách này kết hợp được ưu điểm của cả hai nhưng tăng độ phức tạp — chỉ nên làm khi thực sự cần .htaccess support mà không muốn migrate toàn bộ config.

Khuyến nghị thực tế: Với VPS mới setup từ đầu, chọn Nginx. Với server đang chạy Apache ổn định — không cần migrate chỉ vì Nginx "trendy hơn". Migrate chỉ khi bạn gặp vấn đề thực sự: memory quá cao, không handle được concurrent connections, hoặc cần reverse proxy phức tạp.

← Về danh sách Blog