Andrey Topoleov
Andrey Topoleov

Reputation: 1919

Catching js|css in nginx location regexp

Anybody plaese explain me - why requst on that url - http://localhost/static/css/style.css return 404?

Here is part of my nginx.conf

location ~ /static/(?<doctype>[js|css]+) {

  # root /usr/src/app/public/;

  if ($doctype = "css") {
    set $contnt_type "text/css";
  }
  if ($doctype = "js") {
    set $contnt_type "text/javascript";
  }

  expires 30d;
  add_header X_Cached 1;
  access_log off;

  add_header Cache-Control "public";
  add_header  Content-Type   $contnt_type;

   return 200  "$doctype";
}

Thanks

Upvotes: 0

Views: 698

Answers (2)

Danila Vershinin
Danila Vershinin

Reputation: 9855

Things are less complicated than you want them to be. Changing Content-Type based on a file extension is a trivial task in NGINX and you don't need a dedicated location to achieve that.

Simply edit /etc/nginx/mime.types with the desired value of Content-Type header based on file extension, e.g.:

types {
    text/html       html htm shtml;
    text/css        css;
    text/javascript js;     
    ...
}

Needless to say, editing that file will result in the Content-Type values specified for the entire NGINX installation. Which is fine, for most cases.

If you indeed want to alter Content-Type in a specific location (which I really don't see why, but putting it for completeness), you can do this as well, like so (assuming you know all the possible file types in a given location):

location /static/ {
  types { 
     text/css css;
     text/javascript js; 
     # be sure to add any extra file types you have below:
     # ...
  }   

  expires 30d;
  add_header X_Cached 1;
  access_log off;

  add_header Cache-Control "public";
}

Upvotes: 2

Ivan Shatsky
Ivan Shatsky

Reputation: 15478

You would better use the map block instead of if construction, if is evil!

map $doctype $contnt_type {
    js    "text/javascript";
    css   "text/css";
}

server
    ...
    location ~ ^/static/(?<doctype>js|css)/ {
        expires 30d;
        add_header X-Cached 1;
        access_log off;
        add_header Cache-Control "public";
        add_header Content-Type  $contnt_type;
    }
}

Upvotes: 1

Related Questions