# Nginx

# 参考文档

# 请求流程

请求进来先按照 listen 监听的端口进行 server 块的匹配,如果有多个 server 块监听了相同的端口,那么就会进一步使用 server_name 进行匹配(使用请求头 header 中的 Host 值,Host 值通常是当前访问的域名),如果匹配不到对应的 server 块的话,就会按照从上到下的顺序取第一个 server 块,除非有某个 server 块中配置了 default_server

点击查看详情
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;
 
events {
    worker_connections 1024;
}

http {
    include /etc/nginx/mime.types;
    default_type application/octet-stream;
    
    log_format main '$remote_addr - $remote_user [$time_local] "$request" '
                    '$status $body_bytes_sent "$http_referer" '
                    '"$http_user_agent" "$http_x_forwarded_for"';
    
    access_log /var/log/nginx/access.log main;
    
    sendfile on;
    keepalive_timeout 65;
    gzip on;
    
    # 虚拟主机配置
    server {
        listen 80;
        server_name example.com;
        
        root /var/www/html;
        index index.html index.htm;
        
        location / {
            try_files $uri $uri/ =404;
        }
        
        # PHP处理
        location ~ \.php$ {
            fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
            fastcgi_index index.php;
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
            include fastcgi_params;
        }
        
        # 静态文件缓存
        location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
            expires 30d;
        }
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49

# 常用命令

# 启动

  • nginx,默认启动,配置都使用默认。
  • nginx -c nginx.conf,指定配置文件启动。
  • nginx -p /home/nginx -c nginx.conf,指定运行目录、配置文件启动。

# 关闭

  • nginx -s stop,快速关闭。
  • nginx -s quit,优雅关闭。
  • nginx -s quit,优雅关闭。

# 重新加载

  • nginx -s reload,重新加载。
  • nginx -p /home/nginx -c nginx.conf -s reload,指定运行目录和配置文件重新加载。

# 其他

  • nginx -t,测试配置文件正确性。
  • nginx -T,测试配置文件正确性并输出。

# 日志

  • /nginx/logs
  • /var/log/nginx

# 负载均衡策略

7大负载均衡的常用策略:

  1. 轮询 Round Robin(默认)
  2. 加权轮询 Weight Round Robin
  3. 最少连接 Least Connections
  4. 最短响应时间 Least Time
  5. ip_hash
  6. url_hash
  7. 公平策略 fair

# 轮询策略

轮询是最常见的负载均衡策略。请求按照顺序依次分配给后端服务器,每个请求都按照列表中服务器的顺序进行分发。当请求达到服务器列表的末尾时,重新开始从第一个服务器分发。如后端服务器down掉,能自动剔除。

轮询适用于后端服务器性能相近、无需特别考虑请求的处理时间等情况。

轮询也可以理解为是一个特殊的加权策略,不过服务器组中的各个服务器的权重都是1。

upstream my_backend {
	server backend1.example.com;
	server backend2.example.com;
}

# 后面的均衡策略没有 server ,则说明和这里是一样的,不过多重复。
server {
	listen 80;
	server_name myloadbalancer.example.com;

	location / {
		proxy_pass http://my_backend;
		proxy_set_header Host $host;
		proxy_set_header X-Real-IP $remote_addr;
	}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

# 加权轮询 Weight

加权轮询在轮询的基础上引入权重 weight 因素,即给每个服务器分配一个权重值,用于调节每台服务器处理请求的比例,权重高的服务器将获得更多的请求

这种策略适用于服务器性能不均衡的情况,通过调整权重可以实现更灵活的负载均衡。

weight 代表权重,默认为1,weight 和访问比率成正比,权重越高被分配的客户端也就越多。

upstream my_backend {
    server backend1.example.com weight=3;
    server backend2.example.com weight=2;
    server backend3.example.com weight=1;
}
1
2
3
4
5

# 最少连接 Least Connections

最少连接策略 Least Connections请求分配给当前连接数最少的服务器,以保持服务器的负载均衡。

这种策略可以避免出现某些服务器连接数过载的情况,从而提高系统的整体性能。

upstream my_backend {
    least_conn;
    server backend1.example.com;
    server backend2.example.com;
    server backend3.example.com;
}
1
2
3
4
5
6

# 最短响应时间 Least Time

最短响应时间策略 Least Time请求分配给具有最短平均响应时间的服务器。通过实时监测服务器的响应时间,负载均衡器可以动态调整请求的分发,以确保向用户提供更快的响应和更好的体验。

upstream my_backend {
    least_time header_response time;
    server backend1.example.com;
    server backend2.example.com;
    server backend3.example.com;
}
1
2
3
4
5
6

# 基于 IP 哈希

IP 哈希策略根据请求的源 IP 地址计算哈希值,然后将请求分发到特定的服务器。

相同 IP 地址的请求始终被分发到相同的服务器,这有助于保持会话的一致性,适用于需要会话粘性的应用场景,可解决 session 的问题。

upstream my_backend {
    ip_hash;
    server backend1.example.com;
    server backend2.example.com;
    server backend3.example.com;
}
1
2
3
4
5
6

# 基于 URL 哈希

URL 哈希策略根据请求的 URL 计算哈希值,然后将请求分发到特定的服务器。相同 URL 的请求始终被分发到相同的服务器,这对于缓存和特定资源的分发具有一定的优势。

upstream my_backend {
    hash $request_uri;
    server backend1.example.com;
    server backend2.example.com;
    server backend3.example.com;
}
1
2
3
4
5
6

# 公平策略 Fair

公平策略 fair根据服务器的响应时间和负载情况动态调整请求的分发,以确保每个服务器获得相等的负载。

这种策略可以避免某些服务器被过载或负载不均衡的情况。

upstream my_backend {
    fair;
    server backend1.example.com;
    server backend2.example.com;
    server backend3.example.com;
}
1
2
3
4
5
6

# 配置文件

要在 Nginx 中配置 HTTPS,需要一个 SSL 证书文件(通常是 .pem 格式)和一个私钥文件(.key)。确保替换 your_domain.com/path/to/your_certificate.pem/path/to/your_private.key 为你的域名和文件路径。 这个配置块指示 Nginx 监听 443 端口上的 SSL 连接,并提供你的证书和私钥文件来处理加密。当配置了这些后,需要重启或重新加载 Nginx 以应用新的配置。

点击查看详细配置
# 这是Nginx的主配置文件,通常位于/etc/nginx/nginx.conf
# 配置文件由指令和上下文组成,上下文用大括号{}包围

# 核心配置部分
user nginx;  # 指定运行Nginx的用户和用户组
worker_processes auto;  # 工作进程数,auto表示自动检测CPU核心数
error_log /var/log/nginx/error.log warn;  # 错误日志路径和级别
pid /var/run/nginx.pid;  # 存储主进程ID的文件

# 工作进程配置
events {
    worker_connections 1024;  # 每个工作进程的最大连接数
    multi_accept on;  # 一次接受所有新连接,而不是逐个接受
    use epoll;  # 使用epoll事件模型(Linux高效事件模型)
}

# HTTP服务器配置
http {
    # 基本配置
    include /etc/nginx/mime.types;  # 包含MIME类型定义文件
    default_type application/octet-stream;  # 默认MIME类型
    
    # 日志格式配置
    log_format main '$remote_addr - $remote_user [$time_local] "$request" '
                    '$status $body_bytes_sent "$http_referer" '
                    '"$http_user_agent" "$http_x_forwarded_for"';
    
    access_log /var/log/nginx/access.log main;  # 访问日志路径和格式
    
    # 性能优化相关
    sendfile on;  # 启用高效文件传输模式
    tcp_nopush on;  # 仅在sendfile开启时有效,尽可能减少网络报文数量
    tcp_nodelay on;  # 禁用Nagle算法,提高实时性
    keepalive_timeout 65;  # 客户端连接保持活动的超时时间
    gzip on;  # 启用gzip压缩
    gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
    
    # 虚拟主机配置(服务器块)
    server {
        listen 80;  # 监听80端口
        server_name example.com www.example.com;  # 服务器名称(域名)
        
        # 根目录和索引文件
        root /var/www/html;  # 网站根目录
        index index.html index.htm index.php;  # 默认索引文件
        
        # 错误页面重定向
        error_page 404 /404.html;  # 自定义404错误页面
        error_page 500 502 503 504 /50x.html;
        
        # 位置块(URL路由)
        location / {
            try_files $uri $uri/ =404;  # 尝试按顺序查找文件
        }
        
        # PHP处理(需要安装PHP-FPM)
        location ~ \.php$ {
            fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
            fastcgi_index index.php;
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
            include fastcgi_params;
        }
        
        # 静态文件缓存设置
        location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
            expires 30d;  # 缓存30天
            add_header Cache-Control "public";
        }
        
        # 禁止访问隐藏文件
        location ~ /\.ht {
            deny all;
        }
    }
    
    # 另一个虚拟主机示例(HTTPS配置)
    server {
        listen 443 ssl;  # 监听443端口并启用SSL
        server_name secure.example.com;
        
        # SSL证书配置
        ssl_certificate /etc/nginx/ssl/example.com.crt;
        ssl_certificate_key /etc/nginx/ssl/example.com.key;
        
        # SSL优化配置
        ssl_session_cache shared:SSL:10m;
        ssl_session_timeout 10m;
        ssl_protocols TLSv1.2 TLSv1.3;
        ssl_ciphers HIGH:!aNULL:!MD5;
        ssl_prefer_server_ciphers on;
        
        # 其他配置与HTTP服务器类似
        root /var/www/secure;
        index index.html;
        
        # 强制HTTPS重定向(通常放在HTTP上下文中更合适)
        # location / {
        #     return 301 https://$host$request_uri;
        # }
    }
    
    # HTTP重定向到HTTPS的配置
    server {
        listen 80;
        server_name secure.example.com;
        return 301 https://$host$request_uri;
    }
}

# 邮件服务器代理配置(通常不需要可注释掉)
# mail {
#     ...
# }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
点击查看详细配置

# 讨论区

由于评论过多会影响页面最下方的导航,故将评论区做默认折叠处理。

点击查看评论区内容,渴望您的宝贵建议~
Last Updated: 4/29/2025, 3:12:23 PM