Nginx configuration for caching static files

5,333

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.

Share:
5,333

Related videos on Youtube

Giorgio
Author by

Giorgio

Updated on September 18, 2022

Comments

  • Giorgio
    Giorgio almost 2 years

    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

  • Giorgio
    Giorgio about 9 years
    I tried also with location /app but doesn't make any difference, I still cannot execute the location ~* \.(?:ico|css|js|gif|jpe?g|png)$ directive
  • Giorgio
    Giorgio about 9 years
    If I remove the "*" it stops working and I get 404 on those files (ico, css, js and so on).