Home > front end >  serve django staticfiles with nginx
serve django staticfiles with nginx

Time:12-26

i have django back-end and reactjs front-end. i want to load static files of django back-end with nginx but he can't find anything . gunicorn can find django pages but can't load staticfiles

so i want nginx to serve django page and staticfiles.

this is my settings.py :

STATIC_URL = "/static/"
STATIC_ROOT = os.path.join(BASE_DIR, '/static')

docker-compose :

version: "3.9"
   
services:

  backend:
    build: 
      context: ./backend
    ports:
      - "8000:8000"
    entrypoint: ./entrypoint.sh
 #   command: gunicorn server.wsgi:application --bind 0.0.0.0:8000
    volumes:
      - static:/static

  nginx:
    build: 
      context: .
      dockerfile: ./webserver/Dockerfile
    restart: always
    ports:
      - "80:80"
    volumes:
      - static:/static
    depends_on:
      - backend

      
volumes:
  static:

and this is my default.conf :

upstream api {
    server backend:8000;
}


server {
    listen       80;
    server_name  myapp.loc;

    root /usr/share/nginx/html/frontend1;
    location / {
        try_files $uri /index.html;
    }

    location /admin/ {
        proxy_pass http://api;
    }  

    location /static/ {
        alias /static/;
    }

    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }
}

server {
    listen       80;
    server_name  newapp.loc;

    root /usr/share/nginx/html/frontend2;
    location / {
        try_files $uri /index.html;
    }

    location /admin/ {
        proxy_pass http://api;
    }  

    location /static/ {
        alias /static/;
    }

    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }
}

CodePudding user response:

I think the problem occurs in the nginx config file.

    location /static/ {
        alias /static/;
    }

Just now, it will alias to FRONTEND_ROOT/static/ (in this case, it is /usr/share/nginx/html/frontend1/static/), but what we expected is it should alias to BACKEND_ROOT/static/.

So the easiest way to solve this problem is to write absolute path here, to avoid alias to the frontend directory.

CodePudding user response:

Create seperate entry in /etc/hosts for django.loc

Also make nginx configure for your back which will redirect you, changes in default.conf

server {
    listen       80;
    server_name  django.loc;
    location / {
        proxy_pass http://localhost:8000/;
    }
    location /static/ {
        alias /static/;
    }
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }
}

Try this if not working let me know

  • Related