Move URL with redirects in Nginx

October 3, 2016 135 views
Nginx Node.js

I have a node app running on http://localhost:3000. I set up ssl/https with LetsEncrypt so all requests are 301 redirected to https. Im using Nginx as web server.

I'm trying to move my URL from resume.mydomain.com to mydomain.com/resume.

  1. How do I forward requests to mydomain.com AND mydomain.com/resume to my node app?
  2. If users go to mydomain.com AND resume.mydomain.com they should automatically be redirected to mydomain.com/resume.

How do I do this?

1 Answer

You can forward your request to Node.js app by using proxy_pass directive.
Look at your mydomain.com server block.
It is usually in /etc/nginx/sites-available/default if you didn't changed default settings. You can make it like this:

server {
    listen 443 ssl default_server;
    listen [::]:443 ssl default_server;
    ...
    server_name mydomain.com www.mydomain.com;

    location / {
        return 301 https://mydomain.com/resume$request_uri;    
    }
    location /resume {
        proxy_pass http://localhost:3000/;
    }
    ...
}

This will ensure that your traffic to mydomain.com and mydomain.com/resume will get redirected to Node.js app.
About redirection, just create a server block that will listen on resume.mydomain.com and redirect to mydomain.com/resume.

server {
    listen 80;
    listen [::]:80;
    server_name resume.mydomain.com
    return 301 https://mydomain.com/resume$request_uri;
}

This will listen only for http traffic. If you used https on resume.mydomain.com, you should still make it listen on 443 with cert, so it doesn't report Server not found error if accessed via https.
This should do its job, I hope it isn't a lot late.

After you done with changes, test your nginx with

  • sudo nginx -t

If everything goes well just restart it:

  • sudo systemctl restart nginx

Try and observe results, if it is not working correctly, we will make it :D
Edit: added more informations.

Have another answer? Share your knowledge.