Say you have a Node app running on port 3000, and you want yourdomain.com/app to route to it. With Apache, you can do this entirely through .htaccess using mod_rewrite and mod_proxy.
1. Enable the Modules
You need these three Apache modules:
sudo a2enmod rewrite
sudo a2enmod proxy
sudo a2enmod proxy_http
sudo systemctl restart apache2
2. The .htaccess Rule
Forward everything under /app to http://localhost:3000:
Options +FollowSymLinks -Indexes
IndexIgnore *
DirectoryIndex
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteRule ^app/(.*)$ http://localhost:3000/$1 [P,L]
</IfModule>
Quick breakdown:
[P]— proxy mode (needs mod_proxy).[L]— stop processing more rules if this one matches.^app/(.*)$— catches anything starting with/app/.
3. Good to Know
- Make sure Apache is allowed to proxy to internal ports (check your security config).
- If you’re using VirtualHost, put the rule there instead of
.htaccess— better performance. - Want to forward the whole domain? Just drop the
app/part from the regex.
4. Multiple Apps, Multiple Ports
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteRule ^app1/(.*)$ http://localhost:3001/$1 [P,L]
RewriteRule ^app2/(.*)$ http://localhost:3002/$1 [P,L]
</IfModule>
After setting this up, hitting http://yourdomain.com/app forwards to whatever is running on localhost:3000.
References: