DeveloperBootstrap

JavaScript

React Production Deployment with Nginx

Complete guide to deploying React applications with Nginx, including build optimisation, routing, SSL, and aggressive caching.

What you'll learn

  • Build a React app for production
  • Install and configure Nginx as a static file server
  • Configure SPA routing (redirect all paths to index.html)
  • Set up gzip compression and browser caching headers
  • Obtain and configure SSL with Certbot
  • Implement security headers

Production Build

Bash
1# In your React project directory
2npm install
3npm run build    # Vite → dist/  |  CRA → build/
4
5# Copy build output to server
6scp -r dist/ user@yourserver:/var/www/myapp

Nginx Configuration

NGINX
1# /etc/nginx/sites-available/myapp
2server {
3    listen 80;
4    server_name myapp.example.com;
5
6    root /var/www/myapp;
7    index index.html;
8
9    # SPA routing — send all paths to index.html
10    location / {
11        try_files $uri $uri/ /index.html;
12    }
13
14    # Serve static assets directly
15    location /assets/ {
16        expires 1y;
17        add_header Cache-Control "public, immutable";
18    }
19
20    # Disable caching for index.html
21    location = /index.html {
22        add_header Cache-Control "no-cache, no-store, must-revalidate";
23    }
24}
25
26# Enable site
27sudo ln -s /etc/nginx/sites-available/myapp /etc/nginx/sites-enabled/
28sudo nginx -t && sudo systemctl reload nginx

SSL with Certbot

Bash
1sudo apt install -y certbot python3-certbot-nginx
2sudo certbot --nginx -d myapp.example.com
3# Certbot auto-modifies nginx config and sets up auto-renewal

Caching & Compression

NGINX
1# Add to nginx.conf http block
2gzip on;
3gzip_comp_level 6;
4gzip_types text/plain text/css application/json
5           application/javascript text/xml application/xml
6           image/svg+xml;
7gzip_min_length 1000;
8
9# Enable brotli if module is available
10brotli on;
11brotli_comp_level 6;
12brotli_types text/plain text/css application/json application/javascript;

Security Headers

NGINX
1# Add to server block
2add_header X-Frame-Options "DENY" always;
3add_header X-Content-Type-Options "nosniff" always;
4add_header Referrer-Policy "strict-origin-when-cross-origin" always;
5add_header Permissions-Policy "camera=(), microphone=(), geolocation=()" always;
6add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" always;