Search code examples
djangonginxserver-administration

Nginx fails to load CSS in a particular location


D

I want to use cache for the CSS file on my site, I've this configuration:

server {

   root /webapps/sitoweb;
   listen 443;
   ssl on;
   ssl_certificate /etc/nginx/ssl/bundle.crt;
   ssl_certificate_key /etc/nginx/ssl/privateKey.key;
   ssl_ciphers  HIGH:!aNULL:!MD5:!DSS:!RC4;
   ssl_prefer_server_ciphers on;
   ssl_session_cache shared:SSL:10m;
   ssl_session_timeout 10m;
   ssl_protocols  TLSv1 TLSv1.1 TLSv1.2;
   server_name mysite.com;
   access_log of;

   location /django/ {
      proxy_pass http://127.0.0.1:8001;
      proxy_set_header X-Forwarded-Host $server_name;
      proxy_set_header X-Real-IP $remote_addr;
      add_header P3P 'CP="ALL DSP COR PSAa PSDa OUR NOR ONL UNI COM NAV"';
      add_header 'Access-Control-Allow-Origin' '*';
      add_header 'Access-Control-Allow-Headers' 'Content-Type,Accept';
      add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PUT, DELETE';
   }

}

Now the situation is (Without using Cache):

File in www.mysite.com/homeCSS.css Found

File in www.mysite.com/django/djangoCSS.css Found

I've modify Nging adding this:

   location ~* \.(css|js|gif|jpe?g|png)$ {
      expires 168h;
      add_header Pragma public;
      add_header Cache-Control "public, must-revalidate, proxy-revalidate";
   }

Now the situation is (Using Cache):

File in www.mysite.com/homeCSS.css Found

File in www.mysite.com/django/djangoCSS.css NOT Found

Why the CSS in a declared location (location "django" in this case) is NOT foud?


Solution

  • That location is not found, because the regular expression is preferred over standard matches. That means you turned the .css into a local request instead of a proxy request and so it will look for that CSS file in the configured root. The solution is to repeat that block below the Django location and instead use proxy_set_header and equivalents for the expiration. But it's probably better to have the backend send the correct headers instead.