Update: Creating an Nginx-based web server image – React Edition

This is a short update to Creating a simple Nginx-based web server image which took me about an hour to figure out and 10 seconds to fix…..

404, Ad-Rock’s out the door

Yes, I know it’s “four on the floor, Ad-Rock’s at the door.” While working on hosting one of my project React apps in a Docker image, I noticed that the application loaded fine, but I was getting 404 errors after navigating to a sub-page (like /clients) and then hitting refresh.

I checked the container logs, and lo and behold, there were 404 errors for those paths.

Letting React Router do its thing

As it turns out, my original Nginx configuration was missing a key line:

server { 
  listen 8080;
  server_name localhost;
  port_in_redirect off;
  
  location / {
    root /usr/share/nginx/html;
    index index.html index.htm;

    # The line below is required for react-router
    try_files $uri $uri/ /index.html;
  }
  error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }
}

That little try_files line made sure to push unknown paths back to index.html, where react-router would handle them.

And with that line, the 404s disappeared and the React app was running as expected.


Posted

in

,

by

Tags: