2

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)

1
  • Looks really weird. What happens if you'd add a trailing slash to both location and alias directives: location /static/ { alias /home/user/folder/backend/staticfiles/; } ? Commented Dec 30, 2021 at 3:11

2 Answers 2

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:

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for the answer, and the extra resources. Giving it a try to see how it goes
I get this error "/home/user/folder/backend/staticfiles/index.html" failed (2: No such file or directory) using your answer
Where do you get the error? When restarting nginx or when accessing an url? Which url?
When accessing the / url. And the /admin and others show up as not found
0

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/; } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.