Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Meteor / Iron Router external redirection

So I'm creating a basic vanity URL system, where I can have http://myURL.com/v/some-text, grab an item from the database and redirect to a specific URL based on whether or not the client is mobile/desktop and other features.

I usually build Facebook apps, so in the case of desktop they would be redirected to a Facebook URL, otherwise on mobile I can just use normal routes.

Is there a way to redirect from Iron Router on the server-side to an external website?

this.route('vanity',{
    path: '/v/:vanity',
    data: function(){
        var vanity = Vanity.findOne({slug:this.params.vanity});

        // mobile / desktop detection

        if(vanity){
            if(mobile){
                // Redirect to vanity mobile link
            }else{
                // Redirect to vanity desktop link
            }
        }else{
            Router.go('/');
        }
    }
});
like image 732
ahren Avatar asked Jan 18 '15 22:01

ahren


1 Answers

Here is a simple 302-based redirect using a server-side route:

Router.route('/google/:search', {where: 'server'}).get(function() {
  this.response.writeHead(302, {
    'Location': "https://www.google.com/#q=" + this.params.search
  });
  this.response.end();
});

If you navigate to http://localhost:3000/google/dogs, you should be redirected to https://www.google.com/#q=dogs.

Note that if you would like to respond with a 302 to all request verbs (GET, POST, PUT, HEAD, etc.) you can write it like this:

Router.route('/google/:search', function() {
  this.response.writeHead(302, {
    'Location': "https://www.google.com/#q=" + this.params.search
  });
  this.response.end();
}, {where: 'server'});

This may be what you want if you are doing redirects for SEO purposes.

like image 193
David Weldon Avatar answered Nov 03 '22 09:11

David Weldon