Home > Operation and Maintenance > Nginx > How to configure and optimize Nginx static file service

How to configure and optimize Nginx static file service

WBOY
Release: 2023-05-13 09:04:13
forward
1638 people have browsed it

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;
  }
}
Copy after login

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;
}
Copy after login

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;
}
Copy after login

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;
  #...

}
Copy after login

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;
  }
}
Copy after login

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;
}
Copy after login

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;
}
Copy after login

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;
  #...

}
Copy after login

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;
  #...

}
Copy after login

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;
  #...
  
}
Copy after login

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
Copy after login

相反,在以下命令中,未接受的连接数(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
Copy after login

调整操作系统

将 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;
  # ...

}
Copy after login

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!

Related labels:
source:yisu.com
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template