0
0
Expressframework~5 mins

Nginx as reverse proxy in Express

Choose your learning style9 modes available
Introduction

Nginx as a reverse proxy helps direct web traffic to your Express app safely and efficiently.

You want to serve your Express app on standard web ports (80/443) without running it as root.
You need to handle many users at once and want to improve performance.
You want to add security features like SSL encryption easily.
You want to balance traffic between multiple Express app instances.
You want to hide your Express app's real address from users.
Syntax
Express
server {
    listen 80;
    server_name example.com;

    location / {
        proxy_pass http://localhost:3000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }
}

This config listens on port 80 and forwards requests to your Express app on port 3000.

Headers like Host and Connection help keep the connection smooth and secure.

Examples
Forward only requests starting with /api/ to a backend running on port 4000.
Express
location /api/ {
    proxy_pass http://localhost:4000/api/;
}
Pass the real user IP to the Express app for logging or security.
Express
location / {
    proxy_pass http://localhost:3000;
    proxy_set_header X-Real-IP $remote_addr;
}
Sample Program

This simple Express app listens on port 3000. Nginx will forward web requests to it.

Express
const express = require('express');
const app = express();

app.get('/', (req, res) => {
  res.send('Hello from Express behind Nginx!');
});

app.listen(3000, () => {
  console.log('Express app listening on port 3000');
});
OutputSuccess
Important Notes

Make sure Nginx is installed and running before starting your Express app.

Restart Nginx after changing its config to apply updates: sudo systemctl restart nginx.

Use HTTPS with Nginx for secure connections by adding SSL certificates.

Summary

Nginx acts as a middleman between users and your Express app.

It improves security, performance, and flexibility.

Configuring Nginx correctly helps your app handle real-world web traffic smoothly.