Home > front end >  nginx with react-router /api is a 404 page
nginx with react-router /api is a 404 page

Time:10-14

I'm making a multi container app, react with nginx on front and spring boot on backend.

Before adding nginx I had localhost:3000 as my react app, with localhost:8080 as my spring API. In 3000/themes I could see the react page and with /themes I could access the API because localhost:8080 was the proxy line in package.json.

Adapting this to a docker-compose context I changed to this code below, but in localhost:80/themes I can only access the API, and this is expected. If I put the line "proxy_pass http://backend;" in a "location /api {}", when access localhost/api, I'll get my personalized 404 page, because /api is not a route in react-route and shouldn't be. What I want to have a non-react route to serve my api like "http:backend/api" in the proxy line, and in "localhost/themes" have my themes page, and in a child component access "/themes" and get this API from localhost:8080/themes as I can access from postman.

My nginx.conf right now is:

upstream backend {
    server app-server:8080;
}

server {

    listen 80;

    access_log /var/log/nginx/access.log;
    error_log /var/log/nginx/error.log;

    location / {
        root /usr/share/nginx/html;
        index index.html index.htm;
        try_files $uri $uri/ /index.html =404;
        proxy_pass http://backend;
    }
     
    error_page 401 403 404 index.html;   

    location /public {
        root /usr/local/var/www;
    }
}

And my package.json proxy line is:

"proxy": "http://backend",

CodePudding user response:

You could try to add add a named location for proxy_pass, and append it as the last argument of try_files

upstream backend {
    server app-server:8080;
}

server {

    listen 80;

    access_log /var/log/nginx/access.log;
    error_log /var/log/nginx/error.log;

    location / {
        root /usr/share/nginx/html;
        index index.html index.htm;
        try_files $uri $uri/ @proxy-backend;    
    }

    location @proxy-backend {
        proxy_pass http://backend;
    }
     
    error_page 401 403 404 index.html;   

    location /public {
        root /usr/local/var/www;
    }
}
  • Related