Prevent Nginx from Serving CSS Files as Text/Plain

Nginx fails to load css files

I found an workaround on the web. I added to /etc/nginx/conf.d/default.conf the following:

location ~ \.css {
add_header Content-Type text/css;
}
location ~ \.js {
add_header Content-Type application/x-javascript;
}

The problem now is that a request to my css file isn't redirected well, as if root is not correctly set.
In error.log I see

2012/04/11 14:01:23 [error] 7260#0: *2 open() "/etc/nginx//html/style.css"

So as a second workaround I added the root to each defined location.
Now it works, but seems a little redundant. Isn't root inherited from / location ?

CSS was not loaded because its MIME type

It is usual to place include mime.types; inside the outer http { ... } block, rather than inside a location { ... } block, so that it is system-wide and inherited by all server { ... } blocks and all locations.

Your href="../static/css/ statement is relative, so from the information you provide, we cannot tell whether the URI is being processed by the location /static/ block or the location / block.

You do not have a root (or alias) defined for the location / block, so the false condition of the if (!-f $request_filename) statement will probably always fail with 404.

You may want to set root /var/www/test/my-example in the server { ... } block and allow it to be inherited by some location blocks. The use of alias where a root can be used is discouraged - see this document.

If your CSS files are being served through the proxy_pass http://test_server; then this is the wrong place to be fixing the MIME type.

Nginx server does not load css files from skeleton framework

First of all, you're going to need to tell NGINX to have your static files to obtain a TTL (time to live) via expire headers. Locate this in your NGINX configuration file, if it isn't there. Create a new directive with location

location ~* .(jpg|jpeg|png|gif|ico|css|js)$ {
expires 1s;
}

After this go ahead and purge your files from the server and force it to serve new files.

  • Set sendfile off in nginx.conf
  • Set expires 1s in mysite.conf
  • Explicitly set Cache-Control header: add_header Cache-Control no-cache;

Of course, before doing anything above. If it doesn't require drastic measure, try manually deleting everything in the cache folder: /var/cache/nginx

If that doesn't help then proceed with everything listed here!


After you've successfully purged your server from serving static files. Add this to your NGINX server block to achieve optimization.

gzip             on;
gzip_comp_level 2;
gzip_min_length 1000;
gzip_proxied expired no-cache no-store private auth;
gzip_types text/plain application/x-javascript text/xml text/css application/xml;

It's possible to set expire headers for files that don't change and are served regularly.

location ~* .(jpg|jpeg|png|gif|ico|css|js)$ {
expires 365d;
}


Related Topics



Leave a reply



Submit