Đến nội dung chính
sang.id.vn
Quay lại

Chuyển tiếp request từ path sang port cụ thể bằng .htaccess

English

Giả sử bạn có một app Node chạy ở port 3000 và muốn yourdomain.com/app trỏ tới nó. Với Apache, bạn có thể làm hoàn toàn qua .htaccess bằng mod_rewrite và mod_proxy.

1. Bật các module cần thiết

Cần 3 module Apache:

sudo a2enmod rewrite
sudo a2enmod proxy
sudo a2enmod proxy_http
sudo systemctl restart apache2

2. Cấu hình .htaccess

Forward mọi request từ /app sang http://localhost:3000:

Options +FollowSymLinks -Indexes
IndexIgnore *
DirectoryIndex
<IfModule mod_rewrite.c>
  RewriteEngine on
  RewriteRule ^app/(.*)$ http://localhost:3000/$1 [P,L]
</IfModule>

Giải thích nhanh:

3. Lưu ý

4. Nhiều app, nhiều port

<IfModule mod_rewrite.c>
  RewriteEngine on
  RewriteRule ^app1/(.*)$ http://localhost:3001/$1 [P,L]
  RewriteRule ^app2/(.*)$ http://localhost:3002/$1 [P,L]
</IfModule>

Sau khi config xong, truy cập http://yourdomain.com/app sẽ forward tới app chạy ở localhost:3000.


Tham khảo:


Share this post on:

Bài trước
Tự động deploy JavaScript lên hosting bằng GitHub Workflow
Bài tiếp
Behavioral Design Pattern — Giải thích dễ hiểu với TypeScript