Hướng dẫn cấu hình vhost proxy_pass với Nginx trên Linux

Views: 68 11/04/2026 07:06
Hướng dẫn cấu hình vhost proxy_pass với Nginx trên Linux

1. Proxy_pass là gì?

proxy_pass trong Nginx dùng để chuyển tiếp request từ client đến server backend (Node.js, PHP, Java, API,...).

Hiểu đơn giản:
Client → Nginx → Backend Server

2. Cài đặt Nginx (nếu chưa có)

Ubuntu/Debian:

apt update
apt install nginx -y

CentOS:

yum install nginx -y

 

3. Tạo file vhost (server block)

Thông thường nằm ở:

/etc/nginx/sites-available/
/etc/nginx/conf.d/

Ví dụ tạo file:

nano /etc/nginx/conf.d/example.conf

4. Cấu hình proxy_pass cơ bản

server {
    listen 80;
    server_name example.com;

    location / {
        proxy_pass http://127.0.0.1:3000;

        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_http_version 1.1;
        proxy_set_header Connection "";
    }
}

 

5. Giải thích cấu hình

  • listen 80; → chạy HTTP

  • server_name → domain

  • proxy_pass → địa chỉ backend

  • proxy_set_header → giữ thông tin request gốc

  • X-Forwarded-For → lấy IP thật của client

6. Cấu hình cho WebSocket (nếu dùng Node.js)

location /socket/ {
    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;
}

Cái này bạn đang dùng Node.js WebSocket thì rất quan trọng.

7. Enable vhost (Ubuntu)

ln -s /etc/nginx/sites-available/example.conf /etc/nginx/sites-enabled/

8. Test và reload Nginx

nginx -t
systemctl reload nginx

9. Test hoạt động

  • Truy cập domain → nếu load được app backend là OK

  • Hoặc test bằng curl:

curl -I http://example.com

10. Một số lỗi thường gặp

X 502 Bad Gateway

  • Backend chưa chạy

  • Sai port

  • Firewall block

X 504 Gateway Timeout

  • Backend phản hồi chậm
    👉 Fix:

proxy_read_timeout 300;

11. Cấu hình nâng cao (khuyến nghị)

location / {
    proxy_pass http://127.0.0.1:3000;

    proxy_connect_timeout 60;
    proxy_send_timeout 60;
    proxy_read_timeout 60;

    proxy_buffering off;
}

Tổng kết

  • proxy_pass giúp bạn build hệ thống reverse proxy cực kỳ linh hoạt

  • Dùng nhiều cho:

    • Node.js (Express, Socket.io)

    • API server

    • Load balancing

    • Microservices

Chúc các bạn thành công.

nginx proxy_pass cấu hình nginx reverse proxy vhost nginx linux nginx proxy pass example nginx reverse proxy ubuntu cấu hình nginx server block