Nginx là gì?

Nginx (phát âm là “engine-x”) là một web server mã nguồn mở, mạnh mẽ và hiệu suất cao, được phát triển bởi Igor Sysoev vào năm 2004. Ban đầu được tạo ra để giải quyết vấn đề C10K (xử lý 10,000 kết nối đồng thời), Nginx đã nhanh chóng trở thành một trong những web server phổ biến nhất thế giới.

Nginx không chỉ là web server mà còn có thể hoạt động như:

  • Reverse proxy server
  • Load balancer
  • HTTP cache
  • Mail proxy server
  • API Gateway

Kiến trúc Event-driven và Non-blocking I/O

Điểm mạnh lớn nhất của Nginx nằm ở kiến trúc của nó. Khác với mô hình truyền thống, Nginx sử dụng kiến trúc event-driven và non-blocking I/O (asynchronous).

Cách hoạt động:

  1. Master Process: Một tiến trình chính đọc và đánh giá cấu hình, quản lý worker processes
  2. Worker Processes: Nhiều tiến trình worker xử lý các kết nối thực tế
  3. Event Loop: Mỗi worker process sử dụng event loop để xử lý hàng nghìn kết nối đồng thời

Non-blocking I/O có nghĩa là:

  • Khi một worker process đang chờ I/O (đọc file, database query, network request), nó không bị “block” mà có thể xử lý các request khác
  • Một worker process có thể xử lý hàng nghìn kết nối cùng lúc
  • Tiết kiệm tài nguyên CPU và RAM đáng kể

Ví dụ minh họa:

Apache (Blocking):
Request 1 → Thread 1 → Đợi đọc file (blocked) → Hoàn thành
Request 2 → Thread 2 → Đợi đọc file (blocked) → Hoàn thành
Request 3 → Thread 3 → Đợi đọc file (blocked) → Hoàn thành
→ Cần 3 threads cho 3 requests

Nginx (Non-blocking):
Request 1 → Worker → Đợi I/O → Xử lý Request 2 → Xử lý Request 3 → Request 1 xong
Request 2 → Cùng Worker
Request 3 → Cùng Worker
→ Chỉ cần 1 worker cho 3 requests

So sánh Nginx vs Apache

Tiêu chíNginxApache
Kiến trúcEvent-driven, asynchronousProcess/Thread-based
Xử lý kết nốiMột worker xử lý nhiều kết nốiMột thread/process cho mỗi kết nối
Bộ nhớRất thấp, ổn địnhTăng theo số kết nối
Static contentCực kỳ nhanhNhanh nhưng chậm hơn Nginx
Dynamic contentCần kết hợp với backend (PHP-FPM)Có thể xử lý trực tiếp (mod_php)
Cấu hìnhTập trung, file-basedPhân tán (.htaccess)
ModuleModules phải compile sẵnDynamic loading modules
Rewrite rulesKhác biệt, đơn giản hơnMạnh mẽ với .htaccess
Phù hợp choHigh traffic, static content, reverse proxyShared hosting, dynamic content processing

Khi nào dùng Nginx:

  • Serving static files (HTML, CSS, JS, images)
  • Reverse proxy cho application servers
  • Load balancing
  • High concurrency (nhiều kết nối đồng thời)
  • Cần performance cao với tài nguyên hạn chế

Khi nào dùng Apache:

  • Shared hosting environment
  • Cần .htaccess flexibility
  • Nhiều dynamic modules
  • Legacy applications phụ thuộc vào Apache-specific features

Xu hướng hiện tại: Nhiều hệ thống sử dụng kết hợp: Nginx làm reverse proxy phía trước, Apache xử lý dynamic content phía sau.

Cài đặt Nginx

Trên Ubuntu/Debian

Cài từ official Nginx repository (version mới nhất)

# Cài đặt prerequisites
sudo apt install curl gnupg2 ca-certificates lsb-release ubuntu-keyring

# Import official nginx signing key
curl https://nginx.org/keys/nginx_signing.key | gpg --dearmor \
    | sudo tee /usr/share/keyrings/nginx-archive-keyring.gpg >/dev/null

# Setup repository
echo "deb [signed-by=/usr/share/keyrings/nginx-archive-keyring.gpg] \
http://nginx.org/packages/ubuntu `lsb_release -cs` nginx" \
    | sudo tee /etc/apt/sources.list.d/nginx.list

# Update và cài đặt
sudo apt update
sudo apt install nginx -y

Trên CentOS/RHEL

Từ official Nginx repository:

# Tạo file repo
sudo tee /etc/yum.repos.d/nginx.repo <<EOF
[nginx-stable]
name=nginx stable repo
baseurl=http://nginx.org/packages/centos/\$releasever/\$basearch/
gpgcheck=1
enabled=1
gpgkey=https://nginx.org/keys/nginx_signing.key
module_hotfixes=true
EOF

# Cài đặt
sudo yum install nginx -y

Trên Windows

Download và giải nén

Mở Command Prompt với quyền Administrator:

# Di chuyển vào thư mục Nginx
cd C:\nginx

# Khởi động Nginx
nginx.exe -v

Cấu trúc thư mục và file cấu hình cơ bản

/etc/nginx/
├── nginx.conf                # File cấu hình chính
├── mime.types                # Định nghĩa MIME types
├── fastcgi_params            # FastCGI parameters
├── proxy_params              # Proxy parameters
├── sites-available/          # Các cấu hình site có sẵn
│   └── default               # Virtual host mặc định
├── sites-enabled/            # Symlinks đến sites đang active
│   └── default -> ../sites-available/default
├── conf.d/                   # Additional configurations
├── modules-available/        # Modules có sẵn
└── modules-enabled/          # Modules đang enabled

/var/log/nginx/
├── access.log                # Access logs
└── error.log                 # Error logs

/var/www/html/                # Document root mặc định
└── index.nginx-debian.html

/usr/share/nginx/html/        # Alternative document root

File cấu hình nginx.conf cơ bản

# User chạy Nginx
user www-data;

# Số worker processes (thường = số CPU cores)
worker_processes auto;

# PID file
pid /run/nginx.pid;

# Load dynamic modules
include /etc/nginx/modules-enabled/*.conf;

events {
    # Số kết nối tối đa mỗi worker
    worker_connections 768;
    
    # Phương thức event (epoll cho Linux)
    use epoll;
}

http {
    ##
    # Basic Settings
    ##
    sendfile on;
    tcp_nopush on;
    types_hash_max_size 2048;
    
    # MIME types
    include /etc/nginx/mime.types;
    default_type application/octet-stream;

    ##
    # Logging Settings
    ##
    access_log /var/log/nginx/access.log;
    error_log /var/log/nginx/error.log;

    ##
    # Gzip Settings
    ##
    gzip on;
    gzip_disable "msie6";

    ##
    # Virtual Host Configs
    ##
    include /etc/nginx/conf.d/*.conf;
    include /etc/nginx/sites-enabled/*;
}

File Virtual Host mẫu

server {
    # Port lắng nghe
    listen 80;
    listen [::]:80;

    # Domain name
    server_name example.com www.example.com;

    # Document root
    root /var/www/example.com;
    index index.html index.htm;

    # Access và error logs
    access_log /var/log/nginx/example.com.access.log;
    error_log /var/log/nginx/example.com.error.log;

    # Location block
    location / {
        try_files $uri $uri/ =404;
    }

    # Deny access to .htaccess
    location ~ /\.ht {
        deny all;
    }
}

Quản lý dịch vụ Nginx

Sử dụng systemctl (Linux)

# Khởi động Nginx
sudo systemctl start nginx

# Dừng Nginx
sudo systemctl stop nginx

# Restart Nginx
sudo systemctl restart nginx

# Reload cấu hình (không downtime)
sudo systemctl reload nginx

# Kiểm tra trạng thái
sudo systemctl status nginx

# Enable auto-start khi boot
sudo systemctl enable nginx

# Disable auto-start
sudo systemctl disable nginx

Sử dụng nginx command

# Kiểm tra cấu hình (rất quan trọng trước khi reload)
sudo nginx -t

# Test và show config
sudo nginx -T

# Reload cấu hình
sudo nginx -s reload

# Stop gracefully (chờ requests hiện tại hoàn thành)
sudo nginx -s quit

# Stop ngay lập tức
sudo nginx -s stop

# Reopen log files (sau log rotation)
sudo nginx -s reopen

# Xem version và compile options
nginx -V

Sự khác biệt giữa reload, restart, stop, quit

reload:

  • Không downtime
  • Nginx đọc lại cấu hình
  • Worker processes cũ xử lý xong request hiện tại rồi tắt
  • Worker processes mới được tạo với cấu hình mới
  • Dùng khi: Thay đổi cấu hình, thêm/sửa virtual hosts

restart:

  • Có downtime (ngắn)
  • Stop hoàn toàn rồi start lại
  • Tất cả connections bị đứt
  • Dùng khi: Cài đặt module mới, thay đổi lớn

stop vs quit:

# Stop ngay (kill connections)
sudo nginx -s stop

# Quit gracefully (chờ requests hoàn thành)
sudo nginx -s quit

Kiểm tra dịch vụ Nginx

# Kiểm tra process
ps aux | grep nginx

# Kiểm tra port đang listen
sudo netstat -tulpn | grep nginx
# hoặc
sudo ss -tulpn | grep nginx

# Kiểm tra version
nginx -v

# Test truy cập
curl http://localhost
# hoặc
curl -I http://localhost

Thực hành: Cài đặt và verify

  1. Cài đặt Nginx trên hệ điều hành của bạn
  2. Kiểm tra version và trạng thái
  3. Truy cập http://localhost và xem trang welcome mặc định
  4. Tìm và xem file log access.log

Troubleshooting cơ bản

Lỗi: nginx.conf test failed

# Kiểm tra chi tiết lỗi
sudo nginx -t

# Xem error log
sudo tail -f /var/log/nginx/error.log

Lỗi: Port 80 already in use

# Xem process nào đang dùng port 80
sudo lsof -i :80
# hoặc
sudo netstat -tulpn | grep :80

# Kill process nếu cần
sudo kill -9 <PID>

Lỗi: Permission denied

# Kiểm tra user trong nginx.conf
grep user /etc/nginx/nginx.conf

# Kiểm tra quyền thư mục
ls -la /var/www/html

# Fix ownership
sudo chown -R www-data:www-data /var/www/html

Không truy cập được qua browser

# Kiểm tra firewall (Ubuntu/Debian)
sudo ufw status
sudo ufw allow 'Nginx Full'

# Kiểm tra firewall (CentOS)
sudo firewall-cmd --list-all
sudo firewall-cmd --permanent --add-service=http
sudo firewall-cmd --reload

# Kiểm tra SELinux (CentOS)
sudo getenforce
sudo setenforce 0  # Tạm thời disable để test

Leave a Reply

This site uses cookies to offer you a better browsing experience. By browsing this website, you agree to our use of cookies.