Skip to content Skip to sidebar Skip to footer

Nginx Reverse Proxying To Node.js With Rewrite

I have several apps running behind an Nginx reverse proxy, one of which is a Node server with Express.js. I'm proxying domain.com/demo/app/ to localhost:7003/

Solution 1:

I have made nginx serve static files without even passing those requests to node by adding location directive to the app's nginx configuration file (which is included in nginx.conf):

location ~ /(img|js)/ {
    rewrite ^(.*)$ /public/$1break;
}

location / {
    proxy_pass http://localhost:3000/;
    ...
}

In case request comes to /img or /js directory nginx serves files from /public/img or /public/js directory respectively. All other requests are proxied to node.

You can add more directories if you need (like /css or /views, if you store templates there that you want to use both in node and in browser) and have any directory structure inside those directories, nginx just prepends /public to them and gets files from there without your node app even knowing about it.

Post a Comment for "Nginx Reverse Proxying To Node.js With Rewrite"