Facebook Pixel

How do I cache React static assets in Nginx?

Add a location block matching file extensions (js, css, png, jpg, etc.) with expires 1y and Cache-Control 'public, immutable'. React build files have hashed names, so they can be cached aggressively the hash changes when content changes.

Verify This Answer

Cross-check this information using these trusted sources:

More FAQs in Deploying a React App to EC2 with Nginx Serving the Frontend from the Same Server

Build the React app (npm run build), transfer the dist/ or build/ directory to EC2, configure Nginx with root pointing to the build directory and try_files $uri $uri/ /index.html for client-side routing. Proxy /api/ requests to the Node.js backend on port 3000.

try_files $uri $uri/ /index.html tells Nginx to fall back to index.html for any path that doesn't match a static file. Without this, navigating directly to /profile or /connections returns 404 because Nginx looks for a physical file at that path.

Build the new version (npm run build), transfer the files to EC2 via SCP, or git pull and rebuild on EC2. Nginx serves the new files immediately no restart needed. The hashed file names ensure browsers fetch the new versions.

Still have questions?

Browse all our FAQs or reach out to our support team

Want to upskill yourself?

Our courses are taking a Coffee break, but your curiosity shouldn't. Stay engaged with namastedev linkedin, youtube, discord and other resources while you wait.

0
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.