katericata
katericata

Reputation: 1058

Nginx cache static files from different aplications

I use WordPress as a home page (mysite.com) and Django for the rest (mysite.com/pages). I have single nginx config file for both of them and its working fine. Moreover, they reside in a single server block.

Here are some parts of my configuration:

server {
    ...
    root /var/www/wordpress;
    ...
    location /static/ {
        alias  /home/username/Env/virtenv/mysite/static/;
    }
}

With this both WordPress and Django static files are served. Now I want to cache all static files for 7 days in the browser. If I put this in addition:

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

then the WordPress static files are properly cached, but Django's static files are not even served.

I know this is because the /static/ location is never reached and then Nginx searched Django's files in the root directive which is on server block level and which points to the WordPress location.

I can remove the cache location and add expires 7d; in the /static/ location. This will in opposite cache only the static files of Django.

But how can I make both static resources to be cached for a week?

Upvotes: 1

Views: 2141

Answers (1)

katericata
katericata

Reputation: 1058

Finally I was able to cache both static files - of Wordpress and Django. For requests starting with /static/, I found a way to make Nginx use the /static/ location and not the general static files location, which has the purpose to only cache Wordpress static files.

Its so simple: just use the location modifier ^~.

As this wonderful article of DigitalOcean says:

The block modifier ^~ means that if this block is selected as the best non-regular expression match, regular expression matching will not take place.

Here is the working version of the two location blocks:

location ~*  \.(?:jpg|jpeg|png|svg|gif|ico|css|js)$ {
    # Cache Wordpress or any other public static files
    # of those types for a week in the browser
    expires 7d;
}

location ^~ /static/ {
    alias  /home/username/Env/virtenv/mysite/static/;
    # Cache Django's static files for a week in the browser
    expires 7d;
}

All requests with mysite.com/static/... will match the /static/ location and will not continue to any other regex location.

And for example requests as mysite.com/wp-content/themes/a-theme/style.css?ver=4.7.2 will match the regex location.

Upvotes: 3

Related Questions