Django Nginx Unable to serve Static Files
Nginx won't serve my Django static files while gunicorn serves as expected. I have my settings as:
STATIC_URL = '/static/'
STATICFILES_DIRS = [BASE_DIR / 'static']
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
while my nginx.conf has:
events {}
http {
server {
listen 80;
server_name 127.0.0.1 cloud101.dev www.cloud101.dev;
# Correctly point to your static files directory
# root /usr/src/app/staticfiles;
location /static {
root /usr/src/app/staticfiles;
}
location / {
proxy_pass http://127.0.0.1:8000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
the Dockerfile has:
# pull the official base image
FROM python:3.12.2-bullseye
...
# Install Nginx and dependencies
RUN apt-get install -y nginx
# copy project
COPY . /usr/src/app
COPY website/nginx.conf /etc/nginx/nginx.conf
EXPOSE 8000
RUN python manage.py collectstatic -v 2 --noinput
CMD ["gunicorn", "--bind", "0.0.0.0:8000", "website.wsgi:application"]
gunicorn serves alright but the static files are not served although the default server does. What am I missing?
Replace root with alias.
location /static {
alias /usr/src/app/staticfiles;
}
root means that defined location lies under given root folder. In your case it means /usr/src/app/staticfiles/static which is wrong. Your files are not in staticfiles/static, you just need to map url /static to folder /usr/src/app/staticfiles - this can be done with alias directive.