search
HomeOperation and MaintenanceNginxHow to configure caching of static files in nginx

1. Preparation matters

I think you need a properly working nginx software: install nginx, php 7 and mysql 5.7 (lemp) on ubuntu 16.04 lts.

2 Configure nginx

You can refer to the expires instruction manual to set the http header expiration time. This tag can be placed in http {}, server {}, location {} and other statement blocks or conditional statements in location {} statement blocks. Generally, you will use the expires directive in the location statement block to control your static files, like the following:

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

In the above example, all suffix names are .jpg, .jpeg, .png, .gif, .ico, .css and .js files will expire 365 days after the browser accesses the file. Therefore you need to ensure that the location {} statement block only contains static files that can be cached by the browser.

Then restart the nginx process:

/etc/init.d/nginx reload

You can use the following time settings in the expires directive:

  • off Make expires and cache-control headers unchangeable.

  • epoch Set the expires header to January 1, 1970 00:00:01.

  • max Settings expires The header is December 31, 2037 23:59:59, setting cache-control The maximum survival time is 10 years

  • The time without @ prefix means that this is an expiration time related to the browser access time. You can specify a negative value for the time, which will set the cache-control header to no-cache. For example: expires 10d or expires 14w3d.

  • The time prefixed with @ specifies the time to expire at a certain time of the day, the format is hh or hh:mm, the range of h is 0 to 24, m The range is 0 to 59, for example: expires @15:34.

You can use the following time units:

  • ms: milliseconds

  • s: Seconds

  • m: Minutes

  • # #h: hour

  • d: day

  • w: week

  • m: month (30 days)

  • ##y

    : year (365 days)

  • For example:
1h30m

means one hour and thirty minutes, 1y6m means one year and six months. Note that if you use a header that will expire long in the future, you will need to change the component's file name when the component is modified. Therefore, it is a good idea to specify versions of files. For example, if you have a javascript.js file and you want to modify it, you can add a version number after the modified file name. Then the browser will download the file. If you don't change the file name, the browser will load the (old) file from the cache.

In addition to setting the

expires

header based on the browser access time (such as expires 10d), you can also pass modified ## in front of the time #Keyword, sets the baseline of the expires header to the time the file was modified (please note that this is only valid for the actual file stored on the hard disk).

expires modified 10d;
3 Test

To test whether your configuration is valid, you can use the network analysis function in the developer tools of Firefox, and then use Firefox Access a static file (such as an image). In the output header information, you should be able to see the
expires

header and the

max-age marked cache-control header (max -age tag contains a value in seconds, for example 31536000 refers to the next year)

The above is the detailed content of How to configure caching of static files in nginx. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
NGINX's Impact: Web Servers and BeyondNGINX's Impact: Web Servers and BeyondMay 06, 2025 am 12:05 AM

NGINX initially solved the C10K problem and has now developed into an all-rounder who handles load balancing, reverse proxying and API gateways. 1) It is well-known for event-driven and non-blocking architectures and is suitable for high concurrency. 2) NGINX can be used as an HTTP and reverse proxy server, supporting IMAP/POP3. 3) Its working principle is based on event-driven and asynchronous I/O models, improving performance. 4) Basic usage includes configuring virtual hosts and load balancing, and advanced usage involves complex load balancing and caching strategies. 5) Common errors include configuration syntax errors and permission issues, and debugging skills include using nginx-t command and stub_status module. 6) Performance optimization suggestions include adjusting worker parameters, using gzip compression and

Nginx Troubleshooting: Diagnosing and Resolving Common ErrorsNginx Troubleshooting: Diagnosing and Resolving Common ErrorsMay 05, 2025 am 12:09 AM

Diagnosis and solutions for common errors of Nginx include: 1. View log files, 2. Adjust configuration files, 3. Optimize performance. By analyzing logs, adjusting timeout settings and optimizing cache and load balancing, errors such as 404, 502, 504 can be effectively resolved to improve website stability and performance.

Deploying Applications with NGINX Unit: A GuideDeploying Applications with NGINX Unit: A GuideMay 04, 2025 am 12:03 AM

NGINXUnitischosenfordeployingapplicationsduetoitsflexibility,easeofuse,andabilitytohandledynamicapplications.1)ItsupportsmultipleprogramminglanguageslikePython,PHP,Node.js,andJava.2)Itallowsdynamicreconfigurationwithoutdowntime.3)ItusesJSONforconfigu

NGINX and Web Hosting: Serving Files and Managing TrafficNGINX and Web Hosting: Serving Files and Managing TrafficMay 03, 2025 am 12:14 AM

NGINX can be used to serve files and manage traffic. 1) Configure NGINX service static files: define the listening port and file directory. 2) Implement load balancing and traffic management: Use upstream module and cache policies to optimize performance.

NGINX vs. Apache: Comparing Web Server TechnologiesNGINX vs. Apache: Comparing Web Server TechnologiesMay 02, 2025 am 12:08 AM

NGINX is suitable for handling high concurrency and static content, while Apache is suitable for dynamic content and complex URL rewrites. 1.NGINX adopts an event-driven model, suitable for high concurrency. 2. Apache uses process or thread model, which is suitable for dynamic content. 3. NGINX configuration is simple, Apache configuration is complex but more flexible.

NGINX and Apache: Deployment and ConfigurationNGINX and Apache: Deployment and ConfigurationMay 01, 2025 am 12:08 AM

NGINX and Apache each have their own advantages, and the choice depends on the specific needs. 1.NGINX is suitable for high concurrency, with simple deployment, and configuration examples include virtual hosts and reverse proxy. 2. Apache is suitable for complex configurations and is equally simple to deploy. Configuration examples include virtual hosts and URL rewrites.

NGINX Unit's Purpose: Running Web ApplicationsNGINX Unit's Purpose: Running Web ApplicationsApr 30, 2025 am 12:06 AM

The purpose of NGINXUnit is to simplify the deployment and management of web applications. Its advantages include: 1) Supports multiple programming languages, such as Python, PHP, Go, Java and Node.js; 2) Provides dynamic configuration and automatic reloading functions; 3) manages application lifecycle through a unified API; 4) Adopt an asynchronous I/O model to support high concurrency and load balancing.

NGINX: An Introduction to the High-Performance Web ServerNGINX: An Introduction to the High-Performance Web ServerApr 29, 2025 am 12:02 AM

NGINX started in 2002 and was developed by IgorSysoev to solve the C10k problem. 1.NGINX is a high-performance web server, an event-driven asynchronous architecture, suitable for high concurrency. 2. Provide advanced functions such as reverse proxy, load balancing and caching to improve system performance and reliability. 3. Optimization techniques include adjusting the number of worker processes, enabling Gzip compression, using HTTP/2 and security configuration.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor