1

I have a Node.js app on an Apache server (that is hosting other non-node.js sites). Here's the Apache setup to send all the traffic on www.mysite.com to Node on port 12001:

<VirtualHost *:80>
    ServerAdmin [email protected]
    ServerName  www.mysite.com
    ServerAlias mysite.com www.mysite.com

    ProxyRequests off

    <Proxy *>
        Order deny,allow
        Allow from all
    </Proxy>

    <Location />
        ProxyPass http://localhost:12001/
        ProxyPassReverse http://localhost:12001/
    </Location>

    ErrorLog /var/log/apache2/mysite-error_log
    TransferLog /var/log/apache2/mysite-access_log
</VirtualHost>

And I would like to force all people visiting mysite.com to be redirected to www.mysite.com.

In Node, I can't check req.headers.host as it always equals localhost:12001 and I'm not sure where I'm supposed to put any .htaccess file.

1 Answer 1

1

Just do it in your server config, no need for .htaccess. Add this:

RewriteEngine On
RewriteCond %{HTTP_HOST} !^www.example.com$ [NC]
RewriteCond %{HTTP_HOST} !^$
RewriteRule (.+) http://www.example.com$1 [R=301,L]

(I had to use the standard example.com rather than your example domain as the system rejected that)

This says redirect anything that is not using host www.example.com, unless no host is specified (to avoid loops if serving a request with no host header), to www.example.com.

It is done this way so it can work with misspellings too like ww.example.com (a missing w) if you add the appropriate ServerAlias (perhaps *.example.com) and DNS entries (again a wildcard could be used) and also covers what you asked for, you don't have to do that.

It also preserves the rest of the URL, so:

http://example.com/testing

Will redirect to:

http://www.example.com/testing

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.