Skip to content

Instantly share code, notes, and snippets.

@PowellTravis
Last active January 20, 2019 01:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save PowellTravis/8201e5757382aab4c7529f1e03893138 to your computer and use it in GitHub Desktop.
Save PowellTravis/8201e5757382aab4c7529f1e03893138 to your computer and use it in GitHub Desktop.

Using NGINX as a Reverse Proxy for Express.js

If you want to run a reverse proxy using Nginx as your reverse proxy, you can follow along with this document to get it working fast in no time.

In the default config file you are able to remove everything from the file and add in the code below. (/etc/nginx/sites-available/default) What this code below does is it takes the port 5000 on localhost and push it to the root /. Then after that it takes port 4000 and pushes it to /app. But there is some more in there, so what line 1 under location /app does is it rewrites the url to use the domain which is ^ and adds the /app to it with any extention it uses.

NGINX default config

server {

location / {
        proxy_pass http://localhost:5000;
   }

    location /app {
        rewrite ^/app(.*) /$1 break;
        proxy_pass http://localhost:4000;
    }
}

Node Server

You can add the code below to form the node js server along with a start page.

index.js

const express = require('express');
const path = require('path');
const PORT = process.env.PORT || 5000;
const app = express();


app.get('/', function(req, res){
    res.sendFile(path.join(__dirname+"/index.html"))
});

var server = app.listen(process.env.PORT || 5000, function () {
    var port = server.address().port;
    console.log("Portfolio is working on port " + port);
});
app.js

const express = require('express');
const path = require('path');
const PORT = process.env.PORT || 5000;
const app = express();


app.get('/', function(req, res){
    res.sendFile(path.join(__dirname+"/App1/views/index.html"))
});

var server = app.listen(process.env.PORT || 5000, function () {
    var port = server.address().port;
    console.log("Portfolio is working on port " + port);
});

The ports are hosted localy within the server. When you want to allow access from outside through a subdomain you can use an IPV4 address or domain (123.123.123.123/app or your domain.com/app). You can access these ports through the extention or through a subdomain pointed at the extention or directly at the IPV4 Address.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment