How to Serve React App with Nginx: Simple Guide
To serve a React app with
nginx, build your React app using npm run build and configure nginx to serve the static files from the build directory. Use a server block with root pointing to the build folder and a fallback try_files directive to support React Router.Syntax
This is the basic nginx server block syntax to serve a React app:
server: Defines the server configuration.listen: Sets the port number, usually 80 for HTTP.server_name: Your domain or IP address.root: Path to the React app'sbuilddirectory.index: The default file to serve, usuallyindex.html.try_files: Tries to serve the requested file or falls back toindex.htmlfor client-side routing.
nginx
server {
listen 80;
server_name your_domain.com;
root /path/to/react-app/build;
index index.html;
location / {
try_files $uri $uri/ /index.html;
}
}Example
This example shows a complete nginx configuration to serve a React app located at /var/www/my-react-app/build. It listens on port 80 and serves the app with support for React Router.
nginx
server {
listen 80;
server_name example.com;
root /var/www/my-react-app/build;
index index.html;
location / {
try_files $uri $uri/ /index.html;
}
}Output
When you visit http://example.com, nginx serves the React app's index.html and static files. React Router works correctly because unknown paths fallback to index.html.
Common Pitfalls
Common mistakes when serving React apps with nginx include:
- Not running
npm run buildbefore serving, so files are missing. - Incorrect
rootpath causing 404 errors. - Missing
try_files $uri /index.html;causing React Router to fail on page refresh. - Serving from a subpath without adjusting
basenamein React Router ornginxconfig.
nginx
## Wrong: Missing try_files fallback
server {
listen 80;
server_name example.com;
root /var/www/my-react-app/build;
index index.html;
location / {
# This will cause 404 on client-side routes
try_files $uri $uri/;
}
}
## Right: With fallback
server {
listen 80;
server_name example.com;
root /var/www/my-react-app/build;
index index.html;
location / {
try_files $uri $uri/ /index.html;
}
}Quick Reference
Tips for serving React apps with nginx:
- Always build your React app before serving.
- Set
rootto thebuildfolder. - Use
try_files $uri /index.html;to support client-side routing. - Check file permissions so
nginxcan read files. - Reload
nginxafter config changes withsudo nginx -s reload.
Key Takeaways
Build your React app with npm run build before serving with nginx.
Set nginx root to the React build directory to serve static files.
Use try_files $uri /index.html; to enable React Router support.
Ensure nginx has permission to read the build files.
Reload nginx after configuration changes to apply them.