skip to Main Content

I have a django backend and react frontend.

I want to serve the react on / and use /admin, /api and /auth for Django. Here’s what I have in my Nginx.

upstream backend {
    server 127.0.0.1:8000;
}

server {
    listen 80;

    server_name x.x.x.x;
    root /home/user/folder/frontend;
    index index.html index.htm;

    # for serving static
    location /static {
        alias /home/user/folder/backend/staticfiles;
    }

    # for serving react built files
    location / {
        try_files $uri $uri/ /index.html;
    }
    
    # for everything django
    location ~^/(admin|api|auth) {
      include snippets/proxyinfo.conf;
      proxy_pass http://backend;
    }
}

With the above, the expected behavior is

  • / uses the default root folder, /home/user/folder/frontend and loads the built index files from react accordingly
  • /(admin|api|auth) points to django
  • /static loads static files saved in the /home/user/folder/backend/staticfiles folder.

So not sure why when I hit example.com/static/myfile.css, Nginx is going to /home/user/folder/frontend/static/myfile.css

I’d expect none of the above configuration says that’s what it should do, so what magic is going on?

I thought this answer was self explanatory enough, yet Nginx keeps doing whatever it likes.

I’m using nginx/1.18.0 (if that matters)

2

Answers


  1. Try adding root inside the location / directive too.

    Like this:

    upstream backend {
        server 127.0.0.1:8000;
    }
    
    server {
        listen 80;
        server_name x.x.x.x;
        root /home/user/folder/backend/staticfiles;
    
        # for serving static
        location /static {
            alias /home/user/folder/backend/staticfiles;
        }
    
        # for serving react built files
        location / {
            root /home/user/folder/frontend;
            try_files $uri $uri/ /index.html;
        }
    
        # for everything django
        location ~^/(admin|api|auth) {
          include snippets/proxyinfo.conf;
          proxy_pass http://backend;
        }
    }
    

    Also have a look at those QAs:

    Login or Signup to reply.
  2. from ngix documentation here, it seems you are missing a / at the end of your paths. this trailing / can cause a lot of pain in many languages to be the root cause of many errors.

    please give it a try like this:

    # for serving static
        location /static/ {
            alias /home/user/folder/backend/staticfiles/;
        }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search