David Mckee
David Mckee

Reputation: 1180

How to get redirect from non-www to www on a Meteor app

I am trying to redirect all of my non-www traffic to my www domain. If I type in example.com in, it redirects to the proper https://www.example.com. However, if I type in http://example.com or https://example.com, I get an infinite redirect loop.

I have setup URL forwarding with Namecheap an am hosting on Heroku.

Currently, I have this in my server code, which is creating the redirect loop (without it I just get an error):

WebApp.connectHandlers
    .use(function(req, res, next) {
      var uri = new URI(req.originalUrl);
      if (uri.subdomain() != 'www') {
        uri.normalizeProtocol();
        res.writeHead(301, {
          'Location': 'https://www.example.com' + uri.resource()
        });
        res.end();
      } else {
        next();
      }
    });

I am using URI.js to parse the url. Any ideas on how I can change this?

Upvotes: 0

Views: 345

Answers (1)

edsadr
edsadr

Reputation: 1085

I would recommend to disable the URL forwarding in Namecheap and handle this directly in your app stack.

After that there are few options:

  1. If you are using a proxy like nginx to serve it then this could help:
    How To Redirect www to Non-www with Nginx on CentOS 7

  2. If you are serving directly, then maybe at router level - in Iron Router

     Router.route("addWWW", {
          where: "server",
          path: "*",
          action: function() {
            var fullUrl, host;        
            host = this.request.headers.host;
    
            if (host.indexOf("www") !== 0) {
              fullUrl = "http://wwww." + host + this.request.url;
              this.response.writeHead(HTTP_REDIRECT_PERMANENT, {
                Location: fullUrl
              });
              return this.response.end();
            }
          }
        });
    

Upvotes: 1

Related Questions