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:
[P]— chế độ proxy (cần mod_proxy).[L]— dừng xử lý rule tiếp theo nếu match.^app/(.*)$— bắt mọi request bắt đầu bằng/app/.
3. Lưu ý
- Đảm bảo Apache được phép proxy tới port nội bộ (kiểm tra security config).
- Nếu dùng VirtualHost thì nên đặt rule trong file config VirtualHost thay vì
.htaccess— hiệu năng tốt hơn. - Muốn forward cả domain? Bỏ phần
app/trong regex.
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: