Skip to main content

Nginx Proxy Configuration

This page describes how to configure Nginx to serve as a reverse proxy for the backend API of the CorTest project.

It ensures that incoming HTTP requests are properly routed to the Express server running locally, while serving static files from a separate directory (e.g., an HTML landing page).


Why use Nginx?

In a production environment, your Node.js server should not be directly exposed to the public. Instead, we use Nginx as a reverse proxy:

  • To handle routing based on URL paths.
  • To serve static files efficiently (e.g., landing page).
  • To manage SSL, caching, rate limiting, etc., if needed later.
  • To separate application and web server concerns.

Setup Summary

  • Nginx listens on port 80 (default HTTP port).
  • It forwards specific API calls to Express, which listens on port 2880.
  • All other requests are served from a static folder (e.g., /var/www/html).

Configuration Breakdown

Here is a simplified view of the configuration logic from default.conf:

default.conf
server {
listen 80;
server_name _;

# Proxy API requests to the Express server (port 2880)
location /categories {
proxy_pass http://127.0.0.1:2880/categories;
...
}

location /register {
proxy_pass http://127.0.0.1:2880/register;
limit_except POST {
deny all;
}
...
}

location /profil/ {
proxy_pass http://127.0.0.1:2880/profil/;
...
}

# Serve static HTML files for all other routes
location / {
root /var/www/html;
index index.html;
}
}

Port Mapping Explained

LayerPortRole
Nginx80Public-facing entry point
Express API2880Internal API server (local)

Nginx listens on port 80 and receives all incoming requests. When a request matches a specific API route (/register, /profil/:uid, etc.), Nginx forwards it to the local Express server on port 2880.

This way, your Node.js backend stays encapsulated, and Nginx handles all external traffic.

Route Protection Example

The /register route is sensitive because it modifies the database. The following directive ensures that only POST requests are allowed:

limit_except POST {
deny all;
}

This blocks any accidental or malicious GET, PUT, or DELETE requests to /register.

Static Files

Requests that do not match an API route (e.g., /, /about.html, etc.) fall back to the default handler:

location / {
root /var/www/html;
index index.html;
}

This serves a static frontend or landing page from /var/www/html.

Further Reading

If you're new to Nginx or want to go deeper, you can consult these official resources:

tip

You can find the full default.conf file in the repo here: cortest-api/config/nginx/default.conf