NGINX + Django: Call static files without collectstatic

In a django application, every time whenever there is a change in any static file(css, js) or you add any media file(like image,video) to your application, You have to execute collectstatic command to access them. You can change this default behaviour by making changes in your nginx file serving your web application and change permission of your static file directory.

 
server {
  server_name local.django-react.com;
  location /static/ {
    alias /home/abhishek/Desktop/django-project/core/static/;
    expires 7d;
    add_header Pragma public;
    add_header Cache-Control "public, must-revalidate, proxy-revalidate";
    add_header Vary Accept-Encoding;
    gzip_static on;
  }
  location / {
    proxy_pass http://127.0.0.1:8000;
    proxy_set_header Host $host;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Real-IP $remote_addr;
  }
}
 
server {
  listen 80;
  server_name local.django-react.com;
}

Now, local.django-react.com/static point out to your static file directory “/home/abhishek/Desktop/django-project/core/static/”

Change permission of your static file directory to 777

chmod -R 777 /home/abhishek/Desktop/django-project/core/static/

Now you can access static files directly without executing collectstatic command.

 

Checklist for beginners:

1. Please ensure that you have created symbolic link to enable your site

sudo ln -s /etc/nginx/sites-available/local.django-react.com /etc/nginx/sites-enabled/local.django-react.com

sudo service nginx restart

2. If your are working at local machine and accessing your django appliation at 127.0.0.1:8000, you can access it at virtual host “local.django-react.com” by adding your virtual host in /etc/hosts.

 127.0.0.1     localhost local.django-react.com 

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to Top
Shares