Nginx configuration for caching static files

cachenginx

I have some problem on configuring Nginx to correctly serve an AngularJS application. The server is configured as follow:

www.example.com we have the landing page of the application
www.example.com/app we have the application itself

the path to the application is the following:

/usr/share/nginx/html/example.com/app/

and static files are inside the following:

/usr/share/nginx/html/example.com/app/public/app/assets

Now I would like to set the caching to "no-cache" for all the html files both in landing page and application but set cache to 60 days to all the js, css and images files.

This is my current nginx server configuration:

server {
listen 80;

index index.html;

server_name example.com www.example.com;

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

location ^~ /app {
    alias /usr/share/nginx/html/example.com/app/public/;
    expires -1;
    add_header Pragma "no-cache";
}

location / {
    root /usr/share/nginx/html/example.com;
    expires -1;
    add_header Pragma "no-cache";
    add_header Cache-Control "no-store, no-cache, must-revalidate,  post-check=0, pre-check=0";
  }
}

Now the problem is that the location directive:

location ~* \.(?:ico|css|js|gif|jpe?g|png)$

is never executed, so the cache is set as no-cache as defined in the /app directive.

Any idea?

thanks

Best Answer

A quote from nginx documentation:

If the longest matching prefix location has the “^~” modifier then regular expressions are not checked.

So, the problem here is your location ^~ /app definition. The ^ modifier makes nginx ignore the regular expression for the images.

You should use location /app instead. You don't need regular expression matching in this spot, simple prefix matching is enough.