3

On mobile

I'm trying to improve the page load of my site

enter image description here

I added

# Media: images, icons, video, audio, HTC
location ~* \.(?:jpg|jpeg|gif|png|ico|cur|gz|svg|svgz|mp4|mp3|ogg|ogv|webm|htc|woff2|woff)$ {
    expires 1M;
    access_log off;
    add_header Cache-Control "public";
}

# CSS and Javascript
location ~* \.(?:css|js)$ {
    expires 1y;
    access_log off;
    add_header Cache-Control "public";
}

For some reasons, I feel like the changes that I just added to my Nginx is not taking any effect.

https://developers.google.com/speed/pagespeed/insights/?url=https%3A%2F%2Fwww.bunlongheng.com%2F

How should I debug this further ?

Community
  • 1
  • 1
code-8
  • 54,650
  • 106
  • 352
  • 604

2 Answers2

13

You're missing the max-age directive, from http://nginx.org/en/docs/http/ngx_http_headers_module.html

I don't think you really want CSS and JS files to expire so far out, but I could be wrong.

Also, no logging on images and all these file types? What if you're getting hotlinked or serving CSS/JS files that can't be found.

I would rethink your cache control a bit more.

# Media: images, icons, video, audio, HTC
location ~* \.(?:jpg|jpeg|gif|png|ico|cur|gz|svg|svgz|mp4|mp3|ogg|ogv|webm|htc|woff2|woff)$ {
    expires 1M;
    access_log off;
    # max-age must be in seconds
    add_header Cache-Control "max-age=2629746, public";
}

# CSS and Javascript
location ~* \.(?:css|js)$ {
    expires 1y;
    access_log off;
    add_header Cache-Control "max-age=31556952, public";
}
Dario Zadro
  • 1,143
  • 2
  • 13
  • 23
  • I think this is not what is intended. [Per the docs](http://nginx.org/en/docs/http/ngx_http_headers_module.html#expires) the nginx directive `expires` will set both the `Expires` HTTP-Header to an appropriate date **and** the `max-age` in the Cache-Control header to the appropriate seconds. Responses from the above config will contain two `max-age` fields. (verified with nginx 1.18). – vlz Jul 26 '23 at 16:22
  • Well, that's easily verifiable using `curl -I https://example.com/stylesheet.css` (obviously, replacing the domain/URL with an actual file path). – Dario Zadro Jul 27 '23 at 00:33
0

Two methods to debug http caching which I use are:

  • Go to REDbot.org. You can enter a url and it will show you the relevant HTTP response headers together with notes on what might be wrongly configured.

  • Check the Response headers yourself in the browser (chrome, firefox) to verfiy that your nginx config is applied.

    When e.g. expires 1h is set in your nginx config you should see two response headers:

    Expires: <A date one hour in the future>
    Cache-Control: max-age=3600
    
vlz
  • 911
  • 1
  • 10
  • 18