search
HomeOperation and MaintenanceNginxHow to use Nginx for high-performance static file caching

How to use Nginx for high-performance static file caching

Aug 02, 2023 pm 04:13 PM
nginxhigh performanceStatic file caching

How to use Nginx for high-performance static file caching

Nginx is a lightweight open source web server that has received widespread attention and use for its high performance and high concurrency capabilities. In addition to being a web server, Nginx also has an important function, which is to provide static file caching function, which can greatly optimize the access speed and performance of the website. This article will introduce how to use Nginx for high-performance static file caching and provide corresponding code examples.

  1. Configuring Nginx for static file access
    In order to enable the static file caching function, you first need to configure Nginx to identify and process requests for static files. Usually, static files include images, CSS files, JavaScript files, etc. The following is a simple Nginx configuration example:
server {
    listen 80;
    server_name example.com;

    root /path/to/static/files;

    location ~* .(jpg|jpeg|png|gif|css|js)$ {
        expires 30d;
        access_log off;
    }
}

In the above configuration, listen specifies the port Nginx listens on, and server_name specifies the domain name of the server . root specifies the root directory where the static files are located. The location directive specifies the matching URL pattern and the corresponding processing parameters. In the above configuration, the regular expression ~* .(jpg|jpeg|png|gif|css|js)$ matches the suffix of jpg, jpeg, png, gif, css or js file, expires specifies that the cache validity period is 30 days, and access_log off disables access logging to static files.

  1. Configuring Nginx for static file caching
    In order to enable Nginx's static file caching function, we can add some additional configuration instructions. Here is an example:
location ~* .(jpg|jpeg|png|gif|css|js)$ {
    expires 30d;
    access_log off;
    add_header Cache-Control "public";
    add_header Pragma public;
    etag off;
}

In the above example, the add_header directive adds two header information, namely Cache-Control and Pragma. These two headers tell clients and other caching servers that the cached copy is available for a certain period of time. etag offThe Etag header information is disabled because in some cases, Etag may cause some compatibility issues.

  1. Verify whether the static file cache is effective
    In order to verify whether the static file cache is effective, you can use the browser's developer tools or command line tools to check. In the browser's developer tools, you can view the Cache-Control and Expires fields of the HTTP response header, as well as the size of the response content. If the cache takes effect, after accessing the static file for the first time, you will see that the values ​​of Cache-Control and Expires are consistent with the above configuration when you request again, and the size of the response content will be become very small.

In addition, you can use command line tools such as curl to view HTTP response header information. For example, you can execute the following command to view the HTTP response header information of an image file:

$ curl -I example.com/path/to/image.jpg

If caching is effective, you will see lines similar to the following in the results:

Cache-Control: public, max-age=2592000
Expires: Thu, 10 Aug 2023 08:16:50 GMT
  1. Dynamic Update Cache
    Sometimes we may need to dynamically update the cache, such as when a static file is modified. You can solve this problem by adding the version number to the file name or path. For example, assuming there is a CSS file style.css, we can rename it to style.v1.css and update Nginx’s configuration file to match the new file name. This way, every time the CSS file is modified, you only need to update the version number in the file name.

In addition, Nginx also provides a reload command that can reload the configuration file without stopping the server. For example, you can execute the following command to reload the Nginx configuration file:

$ nginx -s reload

In this way, Nginx will re-read the configuration file, and the updated configuration will take effect immediately.

Summary
By using Nginx for static file caching, the performance and access speed of the website can be significantly improved. In this article, we introduce how to configure Nginx to enable static file access and caching functions, and provide corresponding code examples and verification methods. Hopefully this content will help you optimize your website performance.

The above is the detailed content of How to use Nginx for high-performance static file caching. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
NGINX vs. Apache: Performance, Scalability, and EfficiencyNGINX vs. Apache: Performance, Scalability, and EfficiencyApr 19, 2025 am 12:05 AM

NGINX and Apache are both powerful web servers, each with unique advantages and disadvantages in terms of performance, scalability and efficiency. 1) NGINX performs well when handling static content and reverse proxying, suitable for high concurrency scenarios. 2) Apache performs better when processing dynamic content and is suitable for projects that require rich module support. The selection of a server should be decided based on project requirements and scenarios.

The Ultimate Showdown: NGINX vs. ApacheThe Ultimate Showdown: NGINX vs. ApacheApr 18, 2025 am 12:02 AM

NGINX is suitable for handling high concurrent requests, while Apache is suitable for scenarios where complex configurations and functional extensions are required. 1.NGINX adopts an event-driven, non-blocking architecture, and is suitable for high concurrency environments. 2. Apache adopts process or thread model to provide a rich module ecosystem that is suitable for complex configuration needs.

NGINX in Action: Examples and Real-World ApplicationsNGINX in Action: Examples and Real-World ApplicationsApr 17, 2025 am 12:18 AM

NGINX can be used to improve website performance, security, and scalability. 1) As a reverse proxy and load balancer, NGINX can optimize back-end services and share traffic. 2) Through event-driven and asynchronous architecture, NGINX efficiently handles high concurrent connections. 3) Configuration files allow flexible definition of rules, such as static file service and load balancing. 4) Optimization suggestions include enabling Gzip compression, using cache and tuning the worker process.

NGINX Unit: Supporting Different Programming LanguagesNGINX Unit: Supporting Different Programming LanguagesApr 16, 2025 am 12:15 AM

NGINXUnit supports multiple programming languages ​​and is implemented through modular design. 1. Loading language module: Load the corresponding module according to the configuration file. 2. Application startup: Execute application code when the calling language runs. 3. Request processing: forward the request to the application instance. 4. Response return: Return the processed response to the client.

Choosing Between NGINX and Apache: The Right Fit for Your NeedsChoosing Between NGINX and Apache: The Right Fit for Your NeedsApr 15, 2025 am 12:04 AM

NGINX and Apache have their own advantages and disadvantages and are suitable for different scenarios. 1.NGINX is suitable for high concurrency and low resource consumption scenarios. 2. Apache is suitable for scenarios where complex configurations and rich modules are required. By comparing their core features, performance differences, and best practices, you can help you choose the server software that best suits your needs.

How to start nginxHow to start nginxApr 14, 2025 pm 01:06 PM

Question: How to start Nginx? Answer: Install Nginx Startup Nginx Verification Nginx Is Nginx Started Explore other startup options Automatically start Nginx

How to check whether nginx is startedHow to check whether nginx is startedApr 14, 2025 pm 01:03 PM

How to confirm whether Nginx is started: 1. Use the command line: systemctl status nginx (Linux/Unix), netstat -ano | findstr 80 (Windows); 2. Check whether port 80 is open; 3. Check the Nginx startup message in the system log; 4. Use third-party tools, such as Nagios, Zabbix, and Icinga.

How to close nginxHow to close nginxApr 14, 2025 pm 01:00 PM

To shut down the Nginx service, follow these steps: Determine the installation type: Red Hat/CentOS (systemctl status nginx) or Debian/Ubuntu (service nginx status) Stop the service: Red Hat/CentOS (systemctl stop nginx) or Debian/Ubuntu (service nginx stop) Disable automatic startup (optional): Red Hat/CentOS (systemctl disabled nginx) or Debian/Ubuntu (syst

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

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.