search
HomeOperation and MaintenanceNginxHow to configure and optimize Nginx static file service

Root Directory and Index Files

The root directive specifies the root directory that will be used to search for files. To get the path to the requested file, nginx appends the request uri to the path specified by the root directive. This directive can be placed at any level within the http {} , server {} or location {} context. In the following example, the root directive is defined for the virtual server. It works for all location {} blocks that do not contain a root directive to explicitly redefine the root:

server {
  root /www/data;

  location / {
  }

  location /images/ {
  }

  location ~ \.(mp3|mp4) {
    root /www/media;
  }
}

Here, nginx's uri starting with /images/ will be in the file system's /www/ data/images Search for the corresponding file in the / directory. If the uri ends with a .mp3 or .mp4 extension, nginx searches for the file in the /www/media/ directory because it is defined in a matching location block.

If the request ends with /, nginx treats it as a request for the directory and attempts to find the index file in the directory. The index directive defines the name of the index file (default is index.html). To continue the example, if the request uri is /images/some/path/ , nginx returns the file /www/data/images/some/path/index.html if it exists. If not, nginx returns an http 404 error (not found) by default. To configure nginx to return an automatically generated directory listing, include the on parameter in the autoindex directive:

location /images/ {
  autoindex on;
}

You can list multiple file names in the index directive. nginx searches for files in the specified order and returns the first file it finds.

location / {
  index index.$geo.html index.htm index.html;
}

The $geo variable used here is a custom variable set through the geo directive. The value of the variable depends on the client's IP address.

To return the index file, nginx checks to see if it exists and then does an internal redirect to the new uri obtained by appending the name of the index file to the base uri. Internal redirects cause a new search for the location and may end up in another location, as shown in the following example:

location / {
  root /data;
  index index.html index.php;
}

location ~ \.php {
  fastcgi_pass localhost:8000;
  #...

}

Here, if the uri in the request is /path/ and /data/path/index .html does not exist but /data/path/index.php does, then the internal redirect to /path/index.php will be mapped to the second location. As a result, the request is proxied.

Try a few options

The try_files directive can be used to check if a specified file or directory exists; nginx will redirect internally and return if not The specified status code. For example, to check whether the file corresponding to the request uri exists, use the try_files directive and the $uri variable as follows:

server {
  root /www/data;

  location /images/ {
    try_files $uri /images/default.gif;
  }
}

The file is specified as a uri, using the context of the current location or virtual server The root or alias directive set in is processed. In this case, if the file corresponding to the original uri does not exist, nginx will redirect internally to the uri specified by the last parameter and return /www/data/images/default.gif .

The last parameter can also be a status code (directly starting with an equal sign) or a location name. In the following example, if none of the arguments to the try_files directive resolve to an existing file or directory, a 404 error is returned.

location / {
  try_files $uri $uri/ $uri.html =404;
}

In the next example, if neither the original URI nor the URI with an appended trailing slash resolves to an existing file or directory, the request will be redirected to the specified location and passed to proxy server.

location / {
  try_files $uri $uri/ @backend;
}

location @backend {
  proxy_pass http://backend.example.com;
}

Optimize the performance of served content

Loading speed is a key factor in serving any content. Minor optimizations to your nginx configuration can increase productivity and help achieve optimal performance.

Enable sendfile

By default, nginx handles the file transfer itself and copies the file into a buffer before sending. Enabling the sendfile directive eliminates the step of copying data to a buffer and allows data to be copied directly from one file descriptor to another. Alternatively, to prevent a fast connection from completely occupying a worker process, the sendfile_max_chunk directive can be used to limit the amount of data transferred in a single sendfile() call (in this case 1 mb):

location /mp3 {
  sendfile      on;
  sendfile_max_chunk 1m;
  #...

}

enable tcp_nopush

Use the tcp_nopush directive together with the sendfile on; directive. This allows nginx to send http response headers in a packet immediately after sendfile() gets the chunk of data.

location /mp3 {
  sendfile  on;
  tcp_nopush on;
  #...

}

Enable tcp_nodelay

The tcp_nodelay directive allows overriding nagle's algorithm, which was originally designed to solve the problem of small packets in slow networks. The algorithm combines many small packets into one larger packet and sends the packet with a delay of 200 milliseconds. Today, when serving large static files, data can be sent instantly regardless of packet size. Latency also affects online applications (ssh, online games, online transactions, etc.). By default, the tcp_nodelay directive is set to on, which means nagle's algorithm is disabled. This directive is only used for keepalive connections:

location /mp3 {
  tcp_nodelay    on;
  keepalive_timeout 65;
  #...
  
}

Optimize the backlog queue

其中一个重要因素是 nginx 可以多快地处理传入连接。一般规则是在建立连接时,将其放入侦听套接字的 "listen" (监听)队列中。在正常负载下,队列很小或根本没有队列。但是在高负载下,队列会急剧增长,导致性能不均匀,连接中断,延迟增加。

显示积压队列使用命令 netstat -lan 来显示当前监听队列。输出可能如下所示,它显示在端口 80上的监听队列中,有 10 个未接受的连接,这些连接针对配置的最多 128 个排队连接。这种情况很正常。

current listen queue sizes (qlen/incqlen/maxqlen)
listen     local address     
0/0/128    *.12345      
10/0/128    *.80    
0/0/128    *.8080

相反,在以下命令中,未接受的连接数(192)超过了 128 的限制。当网站流量很大时,这种情况很常见。要获得最佳性能,需要在操作系统和 nginx 配置中增加可以排队等待 nginx 接受的最大连接数。

current listen queue sizes (qlen/incqlen/maxqlen)
listen     local address     
0/0/128    *.12345      
192/0/128    *.80    
0/0/128    *.8080

调整操作系统

将 net.core.somaxconn 内核参数的值从其默认值(128)增加到足以容纳大量流量的值。在这个例子中,它增加到 4096。

  • freebsd 的命令为 sudo sysctl kern.ipc.somaxconn=4096

  • linux 的命令为 1. sudo sysctl -w net.core.somaxconn=4096 2. 将 net.core.somaxconn = 4096 加入到 /etc/sysctl.conf 文件中。

调整 nginx

如果将 somaxconn 内核参数设置为大于 512 的值,请将 backlog 参数增加在 nginx listen 指令以匹配修改:

server {
  listen 80 backlog=4096;
  # ...

}

The above is the detailed content of How to configure and optimize Nginx static file service. 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
The Advantages of NGINX: Speed, Efficiency, and ControlThe Advantages of NGINX: Speed, Efficiency, and ControlMay 12, 2025 am 12:13 AM

The reason why NGINX is popular is its advantages in speed, efficiency and control. 1) Speed: Adopt asynchronous and non-blocking processing, supports high concurrent connections, and has strong static file service capabilities. 2) Efficiency: Low memory usage and powerful load balancing function. 3) Control: Through flexible configuration file management behavior, modular design facilitates expansion.

NGINX vs. Apache: Community, Support, and ResourcesNGINX vs. Apache: Community, Support, and ResourcesMay 11, 2025 am 12:19 AM

The differences between NGINX and Apache in terms of community, support and resources are as follows: 1. Although the NGINX community is small, it is active and professional, and official support provides advanced features and professional services through NGINXPlus. 2.Apache has a huge and active community, and official support is mainly provided through rich documentation and community resources.

NGINX Unit: An Introduction to the Application ServerNGINX Unit: An Introduction to the Application ServerMay 10, 2025 am 12:17 AM

NGINXUnit is an open source application server that supports a variety of programming languages ​​and frameworks, such as Python, PHP, Java, Go, etc. 1. It supports dynamic configuration and can adjust application configuration without restarting the server. 2.NGINXUnit supports multi-language applications, simplifying the management of multi-language environments. 3. With configuration files, you can easily deploy and manage applications, such as running Python and PHP applications. 4. It also supports advanced configurations such as routing and load balancing to help manage and scale applications.

Using NGINX: Optimizing Website Performance and ReliabilityUsing NGINX: Optimizing Website Performance and ReliabilityMay 09, 2025 am 12:19 AM

NGINX can improve website performance and reliability by: 1. Process static content as a web server; 2. forward requests as a reverse proxy server; 3. allocate requests as a load balancer; 4. Reduce backend pressure as a cache server. NGINX can significantly improve website performance through configuration optimizations such as enabling Gzip compression and adjusting connection pooling.

NGINX's Purpose: Serving Web Content and MoreNGINX's Purpose: Serving Web Content and MoreMay 08, 2025 am 12:07 AM

NGINXserveswebcontentandactsasareverseproxy,loadbalancer,andmore.1)ItefficientlyservesstaticcontentlikeHTMLandimages.2)Itfunctionsasareverseproxyandloadbalancer,distributingtrafficacrossservers.3)NGINXenhancesperformancethroughcaching.4)Itofferssecur

NGINX Unit: Streamlining Application DeploymentNGINX Unit: Streamlining Application DeploymentMay 07, 2025 am 12:08 AM

NGINXUnit simplifies application deployment with dynamic configuration and multilingual support. 1) Dynamic configuration can be modified without restarting the server. 2) Supports multiple programming languages, such as Python, PHP, and Java. 3) Adopt asynchronous non-blocking I/O model to improve high concurrency processing performance.

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.

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 Article

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software