How to Setup Nginx with Node.js to Serve Static Files

If you are using Node.js in production to either serve static files or as an API server then you must use a proxy in front of it to secure the application as well as to improve the performance.

If you have read my article on 10 things you should while running Node.js in production then you already know that reverse proxy is the key thing in running Node.js in production.

While you can create a reverse proxy in Node.js itself, I highly recommend you to use Nginx as a proxy.

In this article, we are going to learn how to setup Nginx as a proxy to serve static files.

Why use Nginx with Node.js

One of the core reason to use Nginx with Node.js is to implement a reverse proxy which is a must for production grade system.

Nginx also helps in caching the static resources and doing the SSL operation etc.

How to setup Nginx with Node.js

I am assuming you have Node installed in your system. Install Nginx as well, refer this installation guide.

Once installed, switch to Nginx installation directory using the following command.

cd /etc/nginx/

Now, go to conf.d directory.

cd conf.d

Create new file named sitename.conf.

sitename.conf
upstream backend {
server localhost:3000; #node app address
}

server {
listen 80;
server_name codeforgeek.com; #add your domain

root /var/tools/public;

location / {
try_files $uri @backend;
}

location @backend {
  proxy_pass http://backend;
  proxy_set_header X-Real-IP $remote_addr;
  proxy_set_header Host $host;
  proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  # Following is necessary for Websocket support
  proxy_http_version 1.1;
  proxy_set_header Upgrade $http_upgrade;
  proxy_set_header Connection "upgrade";
 }
}

Let me explain.

  • upstream – custom nginx block where we specify the nodejs server port
  • Server – main entry block where we specify the domain name and port of the Nginx server/
  • location – It tells nginx to look for the content in the specified directory.
  • @backend – the block we specify to redirect the request to our Node.js application

Summary

Nginx is the widely used proxy server with a Node.js application. There is a ton of benefits that come with Nginx, refer to this article for the same.

Shahid
Shahid

Founder of Codeforgeek. Technologist. Published Author. Engineer. Content Creator. Teaching Everything I learn!

Articles: 126