How to redirect non-www to www in Meteor?

I got a domain name from goDaddy and using linode to host my website. I am using Meteor Up to deploy my website.

What is the best practice to do it?

I saw someone suggests to use .htaccess but I am not exactly sure how to do this.

@williams,

In order to use .htaccess you must use Apache in front of Meteor. If you use nginx that’s simple, just do something like this.

If you can redirect this on client (not good because client will already started), you can do this:

Meteor.startup(function () {

  if (location.host.indexOf('www') != -1) {
    location = 'http://site.com';
  }

});

The best way would be to redirect this on server, before loading the client. If someone knows how to do this, I’m curious too.

Tks

1 Like

Don’t use Apache. It’s better to use nginx instead and to use the steps provided in the link above. Also, make sure that the redirect is a 301 and not a 302.

1 Like

I did it (well, the opposite, removing www) with server-side Iron Router for q42.com (sorry about the coffeescript):

Router.route "removeWWW",
  where: "server"
  path: "*"
  action: ->
    console.log "Route: removeWWW (#{@request.url})"
    host = @request.headers.host
    fullUrl = "http://#{host}#{@request.url}"

    if host.indexOf("www") is 0
      @response.writeHead HTTP_REDIRECT_PERMANENT, Location: fullUrl.replace("www.", "")
      @response.end()

Source

@rahul,

I didn’t know about the “*” path, thanks for that!

Tks

2 Likes

Your solution was the simplest and fastest way of correcting this issue for me despite trying to edit my forwarding/redirects through the GoDaddy interface. Are there any drawbacks to using this method? I know you said it’s “not good because the client already started” which I assume means the app is essentially getting rebuilt twice (if they go to your non-www address), using up unnecessary bandwidth and memory but if you or anyone could elaborate why this is not the ideal solution, please let me know.

@rahul

Hi Rahul, I have the same problem.
Can you please share your code for this?

In the meantime i solved this issue with nginx, if somebody is interested about the solution, then you can ask me.

what I did was keep my docker settings mostly as-is (defaults) and then add a new nginx config for a reverse proxy on the server that binds to 127.0.0.1:3000. In the reverse proxy I was able to easily configure nginx