doublesidedstickytape doublesidedstickytape - 1 month ago 14
Node.js Question

Node JS - Nginx - proxy_pass to a subdirectory - Koa

I'm running a Koa app on port 5000, and i'd like Ngnix to serve the app in a sub-directory - e.g:

Here's what I've currently got in

location ^~ /myNodeApp/ {
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_set_header X-NginX-Proxy true;
proxy_pass http://localhost:5000/;

This kind of works... apart from the fact that any redirect e.g
in my Koa app goes to the the nginx web root

Also, it doesn't render anything from my Koa apps'
directory e.g. stylesheets, javascript and images.

What am I doing wrong? Thanks.


I have recently come across the same problem and here's what I did to fix it.

In Server Config:

I had to add

rewrite ^/myNodeApp/(.*)$ /$1 break;

to the NGINX config, in the

location /myNodeApp/ {...}

block, under what you already have in your example.

In client side:

I added

<base href='/myNodeApp/'>

to the <head> of my html files (or pug layout file in my case). This prefixes any links with your subdirectory.

Note that you will need to remove any leading /'s from your existing links. Eg

<link rel="stylesheet" href="layout.css">

instead of

<link rel="stylesheet" href="/layout.css">

That one caught me out for a while.


If you're using Socket.IO, like I am, you'll need to make a few more changes to stop some errors appearing in your console. You need to pass it a path option and specify your subdirectory.

In your html files

var socket = io.connect("/", {path: "/myNodeApp/"})