react, nginx reverse proxy and docker giving 404

Viewed 1167

So my website has two parts:

1- /api, /oauth and /assets locations are redirected to a laravel app and using a simple proxy_pass to their docker port

2- the web app, which is a react app. We make an image of the web app(so no files are transferred to the server) and run it on a port, say 3000.

This is a summary of my Nginx configuration:

server {
        server_name mywebsite.com;

        location /api {
                proxy_pass http://localhost:8080/api;
                proxy_set_header Host $host;
        } //the same with other Laravel paths

        location / {
                proxy_pass http://localhost:3000/;
                proxy_set_header Host $host;
                proxy_redirect off;
        }
}

The problem is if the user goes to a page, say site.com/profile and refreshes it, they get a 404 error. Googling a lot resulted to use try_files .. index.html which works with local files, but not when using proxy_pass and docker images.

More googling had me find a solution that actually worked:

server {
        server_name mywebsite.com;

        location /api {
                proxy_pass http://localhost:8080/api;
                proxy_set_header Host $host;
        } //the same with other Laravel paths

        location / {
                proxy_pass http://localhost:3000/;
                proxy_set_header Host $host;
                proxy_redirect off;
                proxy_intercept_errors on;
                recursive_error_pages on;
                error_page 404 = @rewrite_proxy;
        }

        location @rewrite_proxy {
                rewrite ^/(.*)$ /index.html?$1 break;
                proxy_pass http://localhost:3000;
                proxy_set_header Host $host;
        }
}

It's brilliant and works like a charm. Now the problem is, I'm looking for a solution to give control of ACTUAL 404 errors to the web app, so it can react in different ways depending on the URL. Any suggestions?

1 Answers

Check out this, hope this will help you out

 server {
listen 80;

location /api {
  proxy_pass         http://backend/api;
  proxy_redirect     off;
  proxy_set_header   Host $host;
  proxy_set_header   X-Real-IP $remote_addr;
  proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
  proxy_set_header   X-Forwarded-Host $server_name;
}

location / {
  proxy_pass         http://frontend;
  proxy_redirect     off;
  proxy_set_header   Host $host;
  proxy_set_header   X-Real-IP $remote_addr;
  proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
  proxy_set_header   X-Forwarded-Host $server_name;
  try_files $uri     $uri/ /index.html @backend;
   error_page        405 @backend;
}
location @backend {
    proxy_pass http://frontend;
    proxy_set_header   X-Forwarded-Proto $scheme;
    proxy_set_header   X-Real-IP         $remote_addr;
}

}

Related