Nginx Reverse Proxy Builder · React Vite + API

Nginx Config for React (Vite) SPA + Same-Origin /api/ Proxy (Zero CORS)

Generate an Nginx reverse proxy server block for React Vite + API with URL prefix rewrite previews, Certbot SSL redirects, WebSocket upgrade headers, and Docker DNS checks.

Written & verified by Chathura Prabashana · Updated November 2026

1. Adjust stack settings or load a test scenario2. Inspect live diagnostics3. Copy generated config
Quick-Test Scenarios:

1. Domain, Routing & Upstream

2. TLS, WebSockets & Directives

# /etc/nginx/sites-available/app.myproduct.io.conf
# Generated by OpsCheck DevTools — Validate with: sudo nginx -t && sudo systemctl reload nginx

server {
    listen 80;
    listen [::]:80;
    server_name app.myproduct.io;

    # Redirect all plaintext HTTP traffic permanently to HTTPS
    return 301 https://$host$request_uri;
}

server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    server_name app.myproduct.io;

    # Let's Encrypt Certbot TLS Certificates
    ssl_certificate     /etc/letsencrypt/live/app.myproduct.io/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/app.myproduct.io/privkey.pem;
    ssl_protocols       TLSv1.2 TLSv1.3;
    ssl_ciphers         HIGH:!aNULL:!MD5;
    ssl_prefer_server_ciphers on;

    client_max_body_size 50M;

    # Gzip compression for JSON, JS, CSS, and SVG responses
    gzip on;
    gzip_vary on;
    gzip_proxied any;
    gzip_comp_level 5;
    gzip_min_length 1024;
    gzip_types text/plain text/css application/json application/javascript text/xml application/xml image/svg+xml;

    # Baseline HTTP Security Headers
    add_header X-Frame-Options "SAMEORIGIN" always;
    add_header X-Content-Type-Options "nosniff" always;
    add_header Referrer-Policy "strict-origin-when-cross-origin" always;
    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;

    # Serve built static SPA bundle at root with client-side router fallback
    root /var/www/app/dist;
    index index.html;

    location / {
        try_files $uri $uri/ /index.html;
    }

    location /assets/ {
        expires 1y;
        add_header Cache-Control "public, immutable";
    }

    location /api/ {
        proxy_pass http://127.0.0.1:8000;
        proxy_http_version 1.1;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_set_header X-Forwarded-Host $host;
        proxy_set_header X-Forwarded-Port $server_port;
        proxy_set_header Connection "";

        proxy_connect_timeout 15s;
        proxy_send_timeout 120s;
        proxy_read_timeout 120s;
    }
}
$sudo nginx -t && sudo systemctl reload nginx
URL Routing TransformationPrefix Preserved
GET https://app.myproduct.io/api/usershttp://127.0.0.1:8000/api/users

Strip Prefix OFF: Nginx preserves the full URI so upstream receives '/api/users'.

Configuration Diagnostics

  • infoPrefix Preserved (/api/ Forwarded Intact)

    GET https://app.myproduct.io/api/users -> Upstream receives http://127.0.0.1:8000/api/users. Strip Prefix OFF: Nginx preserves the full URI so upstream receives '/api/users'.

  • passStatic SPA Root (/var/www/app/dist) + Same-Origin Proxy (/api/)

    Serving built SPA files at '/' with try_files $uri $uri/ /index.html while proxying '/api/' on the same domain eliminates browser CORS preflight overhead entirely.

  • infoSingle-Layer CORS Policy Reminder

    This configuration intentionally omits Access-Control-Allow-Origin headers so your upstream backend framework (Laravel, FastAPI, Express, ASP.NET Core) owns CORS cleanly without duplicate header rejections.

Runs locally in your browser. Domain names and upstream topology are never sent to a server.

Common Nginx Error Log Pattern (React Vite + API)

When upstream sockets, timeouts, body limits, or Docker DNS rules are misconfigured for React Vite + API, Nginx typically records an entry matching the log line below inside /var/log/nginx/error.log:

/var/log/nginx/error.log

2026/11/22 20:15:40 [error] 8211#8211: *519 open() "/var/www/app/dist/settings/billing" failed (2: No such file or directory), client: 203.0.113.91, server: app.myproduct.io, request: "GET /settings/billing HTTP/2.0", host: "app.myproduct.io"

Reverse Proxy Architecture & Header Forwarding for React Vite + API

One of the cleanest production patterns for React (Vite), Vue, or Svelte single-page applications is serving the compiled static dist/ bundle directly from Nginx at / while reverse-proxying /api/ to your backend API (Laravel, FastAPI, Express, or ASP.NET Core) under the exact same HTTPS domain. Because the browser loads both the frontend HTML and /api/* responses from https://app.myproduct.io, every fetch call is strictly same-origin; eliminating CORS preflight round-trips and third-party cookie restrictions completely.

To make client-side routing (React Router, TanStack Router, Vue Router) work reliably on deep-link refreshes, Nginx MUST include try_files $uri $uri/ /index.html; inside location /. Without that single directive, clicking links inside the SPA works fine, but pressing F5 on /settings/billing causes Nginx to search disk for a literal file at /var/www/app/dist/settings/billing and return HTTP 404 Not Found.

Caching strategy splits cleanly across two layers: Vite hashes every file inside /assets/* (such as index-B8x9a2.js), allowing Nginx to serve /assets/ with Cache-Control: public, immutable for 1 year. Conversely, /index.html MUST NEVER be cached aggressively; if browsers cache an old index.html after a deployment, users request deleted hashed JS files and encounter blank screens.

Finally, toggle Strip Prefix carefully depending on how your backend defines its routes: if your backend expects /api/users, leave Strip Prefix OFF; if your backend expects /users at root, turn Strip Prefix ON so Nginx appends a trailing slash to proxy_pass and rewrites /api/users cleanly to /users.

Deploying a React (Vite) SPA and its backend API behind the same Nginx origin delivers both faster runtime performance, by removing every cross-origin OPTIONS preflight, and simpler browser security, since HttpOnly session cookies stay strictly first-party. Automate atomic dist/ swaps (or rsync --delete) during CI deployments, keep Cache-Control: no-cache on /index.html while setting immutable 1-year caching on hashed /assets/, and verify in Chrome DevTools that client-side routes refresh cleanly while /api/ 404 errors return authentic JSON from your backend rather than HTML.

Step-by-Step Nginx & React Vite + API Deployment Guide

Apply the Nginx server block above alongside these upstream framework trust-proxy settings so HTTPS detection, real client IPs, and reload safety work reliably in production.

  1. 1Build the React Vite Bundle Using Relative /api Base URLs

    .env.production

    When Nginx serves the SPA and proxies /api/ on the exact same domain, point your React API client at relative "/api" instead of a hardcoded cross-origin domain so dev, staging, and production work without CORS.

    .env.productiondotenv
    # .env.production
    VITE_API_BASE_URL=/api
    
    # Build production bundle and deploy dist/ to Nginx root
    npm run build
    sudo rsync -av --delete dist/ /var/www/app/dist/
  2. 2Prevent Browser Caching of /index.html While Caching /assets/ Forever

    /etc/nginx/sites-available/app.myproduct.io.conf

    Ensure index.html sends Cache-Control: no-cache so browsers immediately pick up newly deployed Vite chunk hashes while /assets/ stays cached for a full year.

    /etc/nginx/sites-available/app.myproduct.io.confnginx
    location = /index.html {
        add_header Cache-Control "no-cache, no-store, must-revalidate";
    }
    
    location / {
        try_files $uri $uri/ /index.html;
    }
    
    location /assets/ {
        expires 1y;
        add_header Cache-Control "public, immutable";
    }
  3. 3Verify Strip Prefix Behavior Against Your Backend Router

    routing checklist

    Confirm whether your upstream API expects /api/users (Strip Prefix OFF: proxy_pass http://127.0.0.1:8000;) or /users (Strip Prefix ON: proxy_pass http://127.0.0.1:8000/;). Mismatching this single trailing slash causes immediate 404 errors on every API call.

    routing checklistbash
    # Strip Prefix OFF -> Upstream receives /api/users
    location /api/ {
        proxy_pass http://127.0.0.1:8000;
    }
    
    # Strip Prefix ON -> Upstream receives /users
    location /api/ {
        proxy_pass http://127.0.0.1:8000/;
    }
  4. 4Test Deep-Link SPA Refresh and Same-Origin API Calls

    terminal

    Validate Nginx, reload, and verify both a client-side route deep link (returns 200 text/html) and an API call (returns 200 application/json).

    terminalbash
    sudo nginx -t && sudo systemctl reload nginx
    curl -I https://app.myproduct.io/settings/billing
    curl -i https://app.myproduct.io/api/health

Common React Vite + API Nginx Reverse Proxy Pitfalls

Review these three production failure modes before reloading Nginx on staging or live servers.

Pitfall 1

404 Not Found on Page Refresh Due to Missing try_files Fallback

Without try_files $uri $uri/ /index.html;, navigating to /dashboard inside React works via the History API, but refreshing the browser or opening a shared link returns Nginx's default 404 page.

Pitfall 2

API 404s Returning index.html Instead of JSON

If a developer accidentally misspells location /api/ (or forgets the /api/ block completely), failed API fetches fall through to location / and receive HTTP 200 HTML (index.html), causing fetch().json() to crash with "Unexpected token < in JSON."

Pitfall 3

Security Headers Disappearing Inside /assets/ Location Block

Remember Nginx's add_header inheritance rule: declaring add_header Cache-Control inside location /assets/ overrides parent server-block add_header directives (like HSTS or X-Content-Type-Options) for that location.

Related Tools

Pair this Nginx reverse proxy block with healthcheck-gated Docker Compose orchestration and verified browser CORS headers:

Frequently Asked Questions

Does proxying /api/ through the same Nginx domain eliminate CORS completely?
Yes. Because the browser sees https://app.myproduct.io for both the SPA and /api/* calls, every request is strictly same-origin; zero OPTIONS preflights, zero Access-Control-Allow-Origin headers required, and first-party SameSite=Lax cookies work reliably across Safari and Chrome.
Why does Nginx return 404 on /assets/main-abc123.js after a deployment?
A user's browser cached the previous index.html referencing an old hashed bundle that was deleted during rsync --delete. Adding Cache-Control: no-cache on location = /index.html ensures users always fetch the newest manifest.
How does Vite server.proxy compare to this Nginx configuration?
Vite's server.proxy in vite.config.ts only runs during local npm run dev. This Nginx server block is the exact production equivalent; serving your static dist/ folder and tunneling /api/ to your backend.
Can I still allow a mobile app or external partner domain to hit /api/?
Yes. Native mobile apps do not enforce browser CORS, and if a separate external web domain needs access to /api/, enable CORS selectively inside your backend framework while Nginx leaves CORS headers untouched.
Browse all 10 Nginx guides →