One of the simplest yet most effective ways to speed up your website is by leveraging browser caching. When a user visits your site, their browser downloads various assets like HTML files, CSS stylesheets, JavaScript files, and images. Browser caching instructs the user's browser to store these assets locally, so on subsequent visits, the browser can load them directly from its cache instead of re-downloading them from your server. This dramatically reduces load times and server traffic.
Nginx provides powerful directives to control how browsers cache your content. The primary mechanism for this is the expires directive, which sets the Expires and Cache-Control HTTP headers. These headers tell the browser for how long it should consider a resource 'fresh' and therefore cacheable.
location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
expires 365d;
add_header Cache-Control "public, no-transform";
}In this example, we're targeting common static asset file extensions (.jpg, .jpeg, .png, .gif, .ico, .css, .js). The expires 365d; directive tells the browser to cache these files for 365 days. The add_header Cache-Control "public, no-transform"; directive further refines caching behavior. public allows any cache (including intermediary proxies) to store the response, while no-transform prevents any modification of the content by intermediaries. For frequently changing content, you'd use a shorter expiration time, perhaps just a few hours or minutes.
You can also specify expiration times using relative units like hours or minutes. For instance, expires 1h; would cache for one hour, and expires 30m; for thirty minutes.
location / {
expires 1h;
}This example applies caching to all resources served from the root location. It's generally a good practice to have different caching strategies for different types of content. Static assets that rarely change can be cached for a very long time, while dynamic content might have much shorter or no caching enabled at the browser level.