Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React-router and nginx

The location block in your nginx config should be:

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

The problem is that requests to the index.html file work, but you're not currently telling nginx to forward other requests to the index.html file too.


Here are my solutions

simple trying:

location / {
    root /var/www/mysite;
    try_files $uri /index.html;
}

no more trying for non-html types:

location / {
    root /var/www/mysite;
    set $fallback_file /index.html;
    if ($http_accept !~ text/html) {
        set $fallback_file /null;
    }
    try_files $uri $fallback_file;
}

no more trying for non-html types and directory (making try_files compatible with index and/or autoindex):

location / {
    root /var/www/mysite;
    index index.html;
    autoindex on;
    set $fallback_file /index.html;
    if ($http_accept !~ text/html) {
        set $fallback_file /null;
    }
    if ($uri ~ /$) {
        set $fallback_file /null;
    }
    try_files $uri $fallback_file;
}

Maybe this is not the exact case here but for anyone running a docker container for their react project with react-router and webpack-dev-server, in my case I had everything I needed in my nginx.conf:

server {
    listen 80;
    location / {
      root   /usr/share/nginx/html;
      index  index.html index.htm;
      try_files $uri $uri/ /index.html;
    } 
    error_page 404 /index.html;
    location = / {
      root /usr/share/nginx/html;
      internal;
    }
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
      root   /usr/share/nginx/html;
    }
  }

But still nginx wouldn't send 404 erros to the root /. After looking into the container I noticed that there's some configs in /etc/nginx/conf.d/default.conf which would somehow overrides my configs, so deleting that file in my dockerfile solved the problem:

...
FROM nginx:alpine
COPY --from=build /app/build /usr/share/nginx/html
RUN rm /etc/nginx/conf.d/default.conf  # <= This line solved my issue
COPY nginx.conf /etc/nginx/conf.d
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]

Here is the solution that works for me in the live server:

I have just followed this tutorial and with the basic Nginx configuration simply just configured the location block.

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