nginx-learn

安装

yum install -y gcc pcre pcre-devel zlib zlib-devel

./configure –prefix=/usr/local/nginx –with-http_gzip_static_module

make

make install

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
vi /usr/lib/systemd/system/nginx.service

[Unit]
Description=nginx - web server
After=network.target remote-fs.target nss-lookup.target
[Service]
Type=forking
PIDFile=/usr/local/nginx/logs/nginx.pid
ExecStartPre=/usr/local/nginx/sbin/nginx -t -c /usr/local/nginx/conf/nginx.conf
ExecStart=/usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf
ExecReload=/usr/local/nginx/sbin/nginx -s reload
ExecStop=/usr/local/nginx/sbin/nginx -s stop
ExecQuit=/usr/local/nginx/sbin/nginx -s quit
PrivateTmp=true
[Install]
WantedBy=multi-user.target

重新加载系统服务

systemctl daemon-reload

启动服务

systemctl start nginx.service

开机启动

systemctl enable nginx.service

Nginx 如何处理请求

nginx 决定哪个server 可以处理请求。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
server {
listen 80;
server_name example.org www.example.org;
...
}

server {
listen 80;
server_name example.net www.example.net;
...
}

server {
listen 80;
server_name example.com www.example.com;
...
}

假设有一个请求都是请求的 80 端口。

  • 通过 Host 请求头
  • 否则,找 default_server
  • 否则,找第一个

负载均衡

The following load balancing mechanisms (or methods) are supported in nginx:

  • round-robin — requests to the application servers are distributed in a round-robin fashion,
  • least-connected — next request is assigned to the server with the least number of active connections,
  • ip-hash — a hash-function is used to determine what server should be selected for the next request (based on the client’s IP address).
1
2
3
4
5
6
# 缺省时为轮询模式
upsteram myapp1 {
server srv1.example.com;
server srv2.example.com;
server srv3.example.com;
}
1
2
3
4
5
6
7
# 最少连接
upsteram myapp1 {
least_conn;
server srv1.example.com;
server srv2.example.com;
server srv3.example.com;
}
1
2
3
4
5
6
7
# 最少连接
upsteram myapp1 {
ip_hash;
server srv1.example.com weight=3; # 可以为不同服务器设置权重哦
server srv2.example.com;
server srv3.example.com;
}

配置 HTTPS 服务器

1
2
3
4
5
6
7
8
9
server {
listen 443 ssl;
server_name www.example.com;
ssl_certificate www.example.com.crt;
ssl_certificate_key www.example.com.key;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2 TLSv1.3;
ssl_ciphers HIGH:!aNULL:!MD5;
...
}

nginx-learn
http://47.97.104.205/2024-04-22/NginxLearn/
作者
Rojer Di
发布于
2024年4月22日
许可协议