When using NginX as a reverse proxy to a NextJS app, static files (.js, .css, etc) come up as 404 not found. The NextJS app works in dev mode. It works in production mode on my machine. It works as a docker container on my machine. But when I deploy it as a docker container in production behind NginX reverse proxy, it 404's every static file.
I've connected to the running docker image and every file is there, right where it should be. I have no idea what is happening, but it's super frustrating!
I created a Demo Repo on GitHub that you can clone and reproduce the issue yourself.
Here's how I set up this demo project:
npx create-next-app@latest
.next.config.js
to include output: "standalone"
nginx
folder at the root of this project has all the nginx config.docker-compose.yaml
file was created to launch both apps.
Thanks in advance for any help!
This happens when NginX is configured to add caching headers to static files via this config block:
# cache static files for 7 days
location ~* \.(?:css(\.map)?|js(\.map)?|jpe?g|png|gif|ico|cur|heic|webp|tiff?|mp3|m4a|aac|ogg|midi?|wav|mp4|mov|webm|mpe?g|avi|ogv|flv|wmv)$ {
expires 7d;
access_log off;
}
When I comment out this block of NginX config, the NextJS app can serve static files again!!
This is kind of dumb. How does this result in 404 files?! This was very difficult to debug, and I hope this post helps at least 1 other person. <3
However, my NginX server serves more than just my NextJS App, including static files on the host machine, so I would like to keep these caching declarations in tact. Some possible solutions are:
Note: Serving static files through a JS server is SLOW. Use a dedicated file server (NginX, CDN, etc) in a public production application. My specific use case is an internal tool at my company, so I more-highly value a simple deployment strategy. Know the pros and cons and make the right choice for your use case.