Home Operation and Maintenance Linux Operation and Maintenance In-depth Nginx configuration article

In-depth Nginx configuration article

Mar 09, 2019 am 10:37 AM
nginx

Commonly used configuration items

At work, we mostly deal with Nginx through its configuration files. Then it is necessary to understand the respective functions of these configuration items. (Related recommendations: Linux Tutorial)

First of all, the content of nginx.conf is usually like this:

...              
...            #核心摸块
events {        #事件模块
   ...
}
http {     # http 模块
    server {      # server块
        location [PATTERN] {  # location块
            ...
        }
        location [PATTERN] {
            ...
        }
    }
    server {
      ...
    }
}
mail {     # mail 模块
     server {    # server块
          ...
    }
}
Copy after login

Let’s look at each one in turn What configuration items do modules generally have?

Core module

user admin; #配置用户或者组
worker_processes 4; #允许生成的进程数,默认为1 
pid /nginx/pid/nginx.pid; #指定 nginx 进程运行文件存放地址 
error_log log/error.log debug; #错误日志路径,级别
Copy after login

Event module

events { 
    accept_mutex on; #设置网路连接序列化,防止惊群现象发生,默认为on 
    multi_accept on; #设置一个进程是否同时接受多个网络连接,默认为off 
    use epoll; #事件驱动模型select|poll|kqueue|epoll|resig
    worker_connections 1024; #最大连接数,默认为512
}
Copy after login

http module

http {
    include       mime.types;   #文件扩展名与文件类型映射表
    default_type  application/octet-stream; #默认文件类型,默认为text/plain
    access_log off; #取消服务日志    
    sendfile on;   #允许 sendfile 方式传输文件,默认为off,可以在http块,server块,location块
    sendfile_max_chunk 100k;  #每个进程每次调用传输数量不能大于设定的值,默认为0,即不设上限
    keepalive_timeout 65;  #连接超时时间,默认为75s,可以在http,server,location块
    server 
    {
            keepalive_requests 120; #单连接请求上限次数
            listen 80; #监听端口
            server_name  127.0.0.1;   #监听地址      
            index index.html index.htm index.php;
            root your_path;  #根目录
            location ~ \.php$
            {
                  fastcgi_pass unix:/var/run/php/php7.1-fpm.sock;
                  #fastcgi_pass 127.0.0.1:9000;
                  fastcgi_index index.php;
                  include fastcgi_params;
            }
    }
}
Copy after login

Configuration item analysis

worker_processes

worker_processes is used to set the number of processes for the Nginx service. This value is the recommended number of CPU cores.

worker_cpu_affinity*

worker\_cpu\_affinity is used to allocate the working core of the CPU to each process. The parameters have multiple binary values, and each group represents one Process, each bit in each group represents the CPU usage of the process, 1 represents use, 0 represents not use. So we use worker\_cpu\_affinity0001001001001000; to bind processes to different cores. By default, worker processes are not bound to any CPU.

worker_rlimit_nofile

Set the maximum number of open files for each process. If not set, the upper limit is the system ulimit-n number, which is generally 65535.

worker_connections

Set the maximum number of theoretically allowed connections for a process. In theory, the larger the better, but it cannot exceed the value of worker_rlimit_nofile.

use epoll

Set the event-driven model to use epoll. epoll is one of the high-performance event-driven libraries supported by Nginx. It is recognized as a very excellent event-driven model.

accept_mutex off

Turn off network connection serialization. When it is set to on, multiple Nginx processes will be serialized to accept connections to prevent multiple Process competition for connections. When there are not many server connections, turning on this parameter will reduce the load to a certain extent. But when the server's throughput is very high, for the sake of efficiency, please turn off this parameter; and turning off this parameter can also make requests more evenly distributed among multiple workers. So we set accept_mutex off;.

multi_accept on

Set a process to accept multiple network connections at the same time.

Sendfile on

Sendfile is a system call launched after Linux 2.0. It can simplify the steps in the network transmission process and improve server performance.

Traditional network transmission process without sendfile:

硬盘 >> kernel buffer >> user buffer >> kernel socket buffer >> 协议栈
Copy after login

Using sendfile() for network transmission process:

硬盘 >> kernel buffer (快速拷贝到 kernelsocket buffer) >>协议栈
Copy after login

tcp_nopush on;

Set data packets to be accumulated and then transmitted together, which can improve some transmission efficiency. tcp_nopush must be used with sendfile.

tcp_nodelay on;

Small data packets are transmitted directly without waiting. The default is on. It seems to be the opposite function of tcp_nopush, but when both sides are on, nginx can also balance the use of these two functions.

keepalive_timeout

The duration of the HTTP connection. Setting it too long will cause too many useless threads. This is considered based on the number of server accesses, processing speed and network conditions.

send_timeout

Set the timeout for the Nginx server to respond to the client. This timeout is only for the time between a certain activity after the two clients and the server establish a connection. , if there is no activity on the client after this time, the Nginx server will close the connection.

gzip on

Enable gzip to compress response data online in real time and reduce the amount of data transmission.

gzip_disable "msie6"

Nginx server does not use the Gzip function to cache application data when responding to these types of client requests. gzip_disable "msie6" is suitable for IE6 browsers. The data is not GZIP compressed.

The commonly used configuration items are roughly as follows. For different business scenarios, some require additional configuration items, which will not be expanded here.

Others

There is a location item in the http configuration, which is used to match the corresponding processing based on the uri in the request. rule.

location search rules

location  = / {
  # 精确匹配 / ,主机名后面不能带任何字符串
  [ config A ]
}
location  / {
  # 因为所有的地址都以 / 开头,所以这条规则将匹配到所有请求
  # 但是正则和最长字符串会优先匹配
  [ config B ]
}
location /documents/ {
  # 匹配任何以 /documents/ 开头的地址,匹配符合以后,还要继续往下搜索
  # 只有后面的正则表达式没有匹配到时,这一条才会采用这一条
  [ config C ]
}
location ~ /documents/Abc {
  # 匹配任何以 /documents/Abc 开头的地址,匹配符合以后,还要继续往下搜索
  # 只有后面的正则表达式没有匹配到时,这一条才会采用这一条
  [ config CC ]
}
location ^~ /images/ {
  # 匹配任何以 /images/ 开头的地址,匹配符合以后,停止往下搜索正则,采用这一条
  [ config D ]
}
location ~* \.(gif|jpg|jpeg)$ {
  # 匹配所有以 gif,jpg或jpeg 结尾的请求
  # 然而,所有请求 /images/ 下的图片会被 config D 处理,因为 ^~ 到达不了这一条正则
  [ config E ]
}
location /images/ {
  # 字符匹配到 /images/,继续往下,会发现 ^~ 存在
  [ config F ]
}
location /images/abc {
  # 最长字符匹配到 /images/abc,继续往下,会发现 ^~ 存在
  # F与G的放置顺序是没有关系的
  [ config G ]
}
location ~ /images/abc/ {
  # 只有去掉 config D 才有效:先最长匹配 config G 开头的地址,继续往下搜索,匹配到这一条正则,采用
    [ config H ]
}
Copy after login

The regular search priority from high to low is as follows:

" = " means starting with Exact matching, for example, in A, only requests at the end of the root directory are matched, and no strings can be included after them.

The beginning of " ^~ " indicates that the uri starts with a regular string and is not a regular match.

The beginning of " ~ " indicates case-sensitive regular matching.

The beginning of " ~* " indicates case-insensitive regular matching.

"/" Universal match, if there is no other match, any request will be matched.

Load balancing configuration

Nginx 的负载均衡需要用到 upstream 模块,可通过以下配置来实现:

upstream test-upstream {
    ip_hash; # 使用 ip_hash 算法分配
    server 192.168.1.1; # 要分配的 ip
    server 192.168.1.2;
}
server {
    location / {       
        proxy_pass http://test-upstream;
    }
}
Copy after login

上面的例子定义了一个 test-upstream 的负载均衡配置,通过 proxy_pass 反向代理指令将请求转发给该模块进行分配处理。

The above is the detailed content of In-depth Nginx configuration article. For more information, please follow other related articles on the PHP Chinese website!

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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to configure cloud server domain name in nginx How to configure cloud server domain name in nginx Apr 14, 2025 pm 12:18 PM

How to configure an Nginx domain name on a cloud server: Create an A record pointing to the public IP address of the cloud server. Add virtual host blocks in the Nginx configuration file, specifying the listening port, domain name, and website root directory. Restart Nginx to apply the changes. Access the domain name test configuration. Other notes: Install the SSL certificate to enable HTTPS, ensure that the firewall allows port 80 traffic, and wait for DNS resolution to take effect.

How to check whether nginx is started How to check whether nginx is started Apr 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 check nginx version How to check nginx version Apr 14, 2025 am 11:57 AM

The methods that can query the Nginx version are: use the nginx -v command; view the version directive in the nginx.conf file; open the Nginx error page and view the page title.

How to create a mirror in docker How to create a mirror in docker Apr 15, 2025 am 11:27 AM

Steps to create a Docker image: Write a Dockerfile that contains the build instructions. Build the image in the terminal, using the docker build command. Tag the image and assign names and tags using the docker tag command.

How to start nginx server How to start nginx server Apr 14, 2025 pm 12:27 PM

Starting an Nginx server requires different steps according to different operating systems: Linux/Unix system: Install the Nginx package (for example, using apt-get or yum). Use systemctl to start an Nginx service (for example, sudo systemctl start nginx). Windows system: Download and install Windows binary files. Start Nginx using the nginx.exe executable (for example, nginx.exe -c conf\nginx.conf). No matter which operating system you use, you can access the server IP

How to run nginx apache How to run nginx apache Apr 14, 2025 pm 12:33 PM

To get Nginx to run Apache, you need to: 1. Install Nginx and Apache; 2. Configure the Nginx agent; 3. Start Nginx and Apache; 4. Test the configuration to ensure that you can see Apache content after accessing the domain name. In addition, you need to pay attention to other matters such as port number matching, virtual host configuration, and SSL/TLS settings.

How to check the name of the docker container How to check the name of the docker container Apr 15, 2025 pm 12:21 PM

You can query the Docker container name by following the steps: List all containers (docker ps). Filter the container list (using the grep command). Gets the container name (located in the "NAMES" column).

How to check whether nginx is started? How to check whether nginx is started? Apr 14, 2025 pm 12:48 PM

In Linux, use the following command to check whether Nginx is started: systemctl status nginx judges based on the command output: If "Active: active (running)" is displayed, Nginx is started. If "Active: inactive (dead)" is displayed, Nginx is stopped.

See all articles