Search code examples
.htaccessmod-rewriteapache2subdomainportforwarding

Change port and host using .htaccess


I am trying to use mod_rewrite to basically port forward a port on a subdomain to another port on another IP.

Like this:

sub.website.com:2000 --> 123.45.67.891:3000 

How could this be accomplished using a .htaccess file with mod_rewrite?

I have tried the following but to no avail:

RewriteCond %{HTTP_HOST} ^sub.website.com$ [NC]
RewriteCond %{SERVER_PORT} ^2000$
RewriteRule ^(.*)$ https://123.45.67.891:3000/$1 [L,R=302]

Solution

  • Playing with your rules, I found out that HTTP_HOST includes the port number. So the rules should look like

    RewriteCond %{HTTP_HOST} ^sub.website.com:2000$ [NC]
    RewriteCond %{SERVER_PORT} ^2000$
    RewriteRule ^(.*)$ https://123.45.67.891:3000/$1 [L,R=302]
    

    If you want to test against server name alone, you could use %{SERVER_NAME} as @faa suggested in the comments

    RewriteCond %{SERVER_NAME} ^sub.website.com$ [NC]