网址导航:
官网nginx.org
www.nginx.com
常用参数
一、 nginx的基本信息
1. 什么是nginx
—Nginx (engine x) 是一个高性能的HTTP和反向代理web服务器,同时也提供了IMAP/POP3/SMTP服务。
—Nginx是一款轻量级的Web 服务器/反向代理服务器及电子邮件(IMAP/POP3)代理服务器,在BSD-like 协议下发行。其特点是占有内存少,并发能力强,事实上nginx的并发能力在同类型的网页服务器中表现较好,中国大陆使用nginx网站用户有:百度、京东、新浪、网易、腾讯、淘宝等。
2. nginx的优点
(1)跨平台、配置简单;
(2)非阻塞、高并发连接:处理2-3万并发连接数,官方监测能支持5万并发;
(3)内存消耗小:开启10个nginx才占150M内存,Nginx采取了分阶段资源分配技术;
(4)nginx处理静态文件好,耗费内存少;
(5)内置的健康检查功能:如果有一个服务器宕机,会做一个健康检查,再发送的请求就不会发送到宕机的服务器了。重新将请求提交到其他的节点上。
(6)节省宽带:支持GZIP压缩,可以添加浏览器本地缓存;
(7)稳定性高:宕机的概率非常小
(8)master/worker结构:一个master进程,生成一个或者多个worker进程。
(9)接收用户请求是异步的:浏览器将请求发送到nginx服务器,它先将用户请求全部接收下来,再一次性发送给后端web服务器,极大减轻了web服务器的压力;
(10)一边接收web服务器的返回数据,一边发送给浏览器客户端;
(11)网络依赖性比较低,只要ping通就可以负载均衡;
(12)事件驱动:通信机制采用epoll模型。
3. nginx和Apache的区别
两者最核心的区别在于apache是同步多进程模型,一个request对应一个进程,而nginx是异步的,多个连接(万级别)可以对应一个进程。
一般来说,需要性能的web服务,用nginx,如果不需要性能只求稳定,更考虑Apache,后者的各种模块实现的比前者好很多,更通用的方案是,前端nginx抗并发,后端apache集群,配合起来会更好。
二、nginx的搭建部署
1、安装所需插件
1.1 安装gcc
gcc是linux下的编译器,它可以编译 C,C++,Ada,Object C和Java等语言
yum install -y gcc
gcc -v 查看gcc版本
1.2安装pcre-devel
pcre是一个perl库,包括perl兼容的正则表达式库,nginx的http模块使用pcre来解析正则表达式,所以需要安装pcre库。
yum install -y pcre-devel
1.3 安装openssl
openssl是web安全通信的基石,没有openssl,可以说我们的信息都是在裸奔
yum install -y openssl-devel
2. 安装nginx
wget https://nginx.org/download/nginx-1.20.1.tar.gz 下载安装包
tar zxf nginx-1.20.1.tar.gz 解压
vim /root/nginx-1.20.1/auto/cc/gcc 关闭debug
#debug
#CFLAGS="$CFLAGS -g"
./configure --prefix=/usr/local/nginx --with-threads --with-file-aio --with-http_ssl_module --with-http_stub_status_module 编译
make
make install
3. 初始化配置nginx
ln -s /usr/local/nginx/sbin/nginx /usr/local/sbin/ 建立软链接开启全局nginx
which nginx
nginx -t 检测语法
nginx 开启服务
netstat -antlp 查看端口
ps ax | grep nginx 查看进程
useradd -d /usr/local/nginx/ -M -s /sbin/nologin nginx 建立nginx的管理用户
vim /usr/local/nginx/conf/nginx.conf 编辑初始化配置文件
user nginx; 管理用户
worker_processes 2或者auto; 工作进程数,不得大于cpu内核数
worker_connections 65535; 单个工作进程并发连接数
}
vim /etc/security/limits.conf
nginx - nofile 65536 worker进程的最大打开文件数限制,大于单个工作进程并发连接数
nginx -s reload 重置服务不报错
nginx -s stop 停止服务
cd /usr/lib/systemd/system 开启systemd启动
vim nginx.service
[Unit] 对服务的说明
Description=The NGINX HTTP and reverse proxy server 描述服务
After=syslog.target network.target remote-fs.target nss-lookup.target 描述服务类别
[Service] 服务的一些具体运行参数的设置
Type=forking 后台运行的形式
PIDFile=/usr/local/nginx/logs/nginx.pid PID文件的路径
ExecStartPre=/usr/local/sbin/nginx -t 启动准备
ExecStart=/usr/local/sbin/nginx 启动命令
ExecReload=/usr/local/sbin/nginx -s reload 重启命令
ExecStop=/bin/kill -s QUIT $MAINPID 停止命令
PrivateTmp=true 给服务分配临时空间
[Install]
WantedBy=multi-user.target 服务用户的模式
systemctl daemon-reload 刷新服务列表
systemctl enable --now nginx.service 启动服务
systemctl status nginx 查看nginx状态
vim /usr/local/nginx/html/index.html
1111
nginx -s reload
4. 测试
宿主机中测试:
vim /etc/hosts
172.25.28.1 www.westos.org
curl www.tao.com
1111 成功
三、并发优化
ulimit -a 可以查看用户可以打开文件的限制 ##open files
sysctl -a | grep file ##打开文件的限制
///fs.file-max = 183593
free -m
四、负载均衡+反向代理
4.1 负载均衡
server1:
scp -r /usr/local/nginx/ root@172.25.128.2:/usr/local/
scp -r /usr/local/nginx root@server3:/usr/local/
server2:
vim /usr/local/nginx/html/index.html
2222
vim /usr/local/nginx/conf/nginx.conf
#user nginx;
worker_processes auto;
worker_connections 1024;
ln -s /usr/local/nginx/sbin/nginx /usr/local/sbin/
nginx
server3:
vim /usr/local/nginx/html/index.html
3333
vim /usr/local/nginx/conf/nginx.conf
#user nginx;
worker_processes auto;
worker_connections 1024;
ln -s /usr/local/nginx/sbin/nginx /usr/local/sbin/
nginx
server1:
vim /usr/local/nginx/conf/nginx.conf
http {
upstream tom { 负载均衡器upstream
server 172.25.128.2:80;
server 172.25.128.3:80;
}
include mime.types;
default_type application/octet-stream;
server {
listen 80; 配置监听端口号
server_name www.tao.org; 配置访问域名,域名可以有多个,用空格隔开
location / { 对以/的地址进行负载均衡
proxy_pass http://tom; 反向代理器,设置被代理服务器的端口或套接字,以及URL
}
}
nginx -t
nginx -s reload
宿主机测试:
curl www.tao.com
3333
2222
3333
2222
4.2 备用机
当所有后端主机都出现问题时,备用机可以暂时运行,但是风险很高,需要及时修理后端服务器。
在server1主机中设定负载均衡中本机可以作为备用机,检测语法,重启服务。同时编辑发布文件。
server1:
vim /usr/local/nginx/conf/nginx.conf
http {
upstream tom {
server 172.25.28.2:80;
server 172.25.28.3:80;
server 172.25.28.1 backup;
}
nginx -s reload
server2/server3:
nginx -s stop
宿主机测试:
curl www.tao.com
1111
1111
4.3 改变权重,默认为1
在server1主机中修改配置文件,增加server2主机的权重,检测语法,重启服务。
server1:
vim /usr/local/nginx/conf/nginx.conf
http {
upstream tom {
server 172.25.28.2:80 `weight=2`;
server 172.25.28.3:80;
server 172.25.28.1 backup;
}
nginx -s reload
宿主机测试:
curl www.tao.com
3333
2222
2222
3333
2222
2222
4.4 ip_hash
ip_hash根据访问的ip进行均衡;
会对后端做健康检测,如果server2出问题,则调度server3
server1:
vim /usr/local/nginx/conf/nginx.conf
http {
upstream tom {
ip_hash;
server 172.25.28.2:80 weight=2;
server 172.25.28.3:80;
#server 172.25.28.1 backup; ip_hash模式需要注释backup
}
nginx -s reload
宿主机测试:
curl www.tao.com
2222
2222 同一ip分配给一个服务器
2222
server2:
nginx -s stop
宿主机测试:
curl www.tao.com
3333
3333 失败自动切换
3333
server3:
nginx -s stop
宿主机测试:
curl www.tao.com
502 Bad Gateway 当所有服务器关闭时显示502
五、平滑升级
1.版本升级
在server1主机中,修改配置文件,设定工作进程数为2,安装一个比当前版本高的nginx,重新编译(configure–makefile–make三步曲)。
下载nginx新版本软件,正常执行./configure和make但不要执行make install。
server1:
nfginx -v 显示当前版本信息
nginx version: nginx/1.20.1
wget https://nginx.org/download/nginx-1.21.2.tar.gz
tar zxf nginx-1.21.2.tar.gz
cd nginx-1.21.2/
./configure --prefix=/usr/local/nginx --with-threads --with-file-aio --with-http_ssl_module --with-http_stub_status_module
make
cp /usr/local/nginx/sbin/nginx /usr/local/nginx/sbin/nginx.old 旧版币备份
\cp -f /root/nginx-1.21.2/objs/nginx /usr/local/nginx/sbin 复制新版本nginx
ps ax | grep nginx 获取当前nginx主进程pid,即master进程。开启新版本。关闭worker进程但保留主进程master
kill -USR2 原进程pid 向原来的nginx的master进程发送信号,不再接收新的请求,新的nginx程序开启worker进程,并且开始接收请求
ps ax | grep nginx 显示新旧两个master,四个worker
kill -WINCH 原进程pid 关闭原worker进程但保留master:为了回退
curl localhoat -I 查看版本号
2. 版本回退
此时新版本已经打开
因为有时觉得旧版本更好,所以保留旧版本的主进程即为了回退,则只关闭worker,保留master
kill -HUP 原进程pid #唤醒原进程
ps ax | grep nginx #查看进程
kill -WINCH 新进程pid #回收新版本进程
kill -QUIT 新进程pid #关闭新版本进程
六、算法扩展
有时nginx并不支持一些算法,当我们需要使用时,则需要进行扩展。
比如sticky模块,nginx本身不支持,当在配置文件中写入并调用时,会报错。
sticky算法模块
sticky工作原理:
Sticky是基于cookie的一种负载均衡解决方案,通过分发和识别cookie,使来自同一个客户端的请求落在同一台服务器上,默认cookie标识名为route:
1.客户端首次发起访问请求,nginx接收后,发现请求头没有cookie,则以轮询方式将请求分发给后端服务器。
2.后端服务器处理完请求,将响应数据返回给nginx。
3.此时nginx生成带route的cookie,返回给客户端。route的值与后端服务器对应,可能是明文,也可能是md5、sha1等Hash值。
4.客户端接收请求,并保存带route的cookie。
5.当客户端下一次发送请求时,会带上route,nginx根据接收到的cookie中的route值,转发给对应的后端服务器。
sticky模块与Ip_hash的区别:
sticky模块与Ip_hash都是与负载均衡算法相关,但又有区别
1.ip hash,根据客户端的IP的hash进行匹配绑定,
客户端将会与一个后端服务器绑定,一定程度上解决了集群部署环境下session共享的问题
2.sticky,根据服务器给客户端的cookie,客户端再次请求时会带上此cookie,nginx会把有此cookie的请求转发到颁发cookie的服务器上
推荐使用sticky算法
模块设置步骤
vim /usr/local/nginx/conf/nginx.conf
http {
upstream tom {
#ip_hash;
sticky;
server 172.25.28.2:80 weight=2;
server 172.25.28.3:80;
server 172.25.28.1 backup;
}
nginx -t 报错
nginx: [emerg] unknown directive "sticky" in /usr/local/nginx/conf/nginx.conf:20
nginx: configuration file /usr/local/nginx/conf/nginx.conf test failed
vim /usr/local/nginx/conf/nginx.conf 注销sticky
#sticky;
nginx -s stop
iptables -t nat -I POSTROUTING -s 172.25.28.0/24 -j MASQUERADE 火墙策略(真机)
wget http://172.25.28.250/pub/docs/lamp/nginx-goodies-nginx-sticky-module-ng-08a395c66e42.zip 下载sticky压缩包
unzip nginx-goodies-nginx-sticky-module-ng-08a395c66e42.zip 解压
./configure --prefix=/usr/local/nginx --with-threads --with-file-aio --with-http_ssl_module --with-http_stub_status_module --add-module=/root/nginx-goodies-nginx-sticky-module-ng-08a395c66e42
make
\cp -f /root/nginx-1.20.1/objs/nginx /usr/local/nginx/sbin/
vim /usr/local/nginx/conf/nginx.conf
http {
upstream tom {
#ip_hash;
sticky; 打开sticky
server 172.25.28.2:80 weight=2;
server 172.25.28.3:80;
#server 172.25.28.1 backup; !!!sticky与backup冲突,注释backup
}
nginx
宿主机测试:
curl www.tao.com sticky针对cookie,所以此命令下不适用
2222
3333
2222
3333
浏览器www.tao.com 成功
2222
2222
2222
七、nginx限流
准备实验素材
mkdir /usr/local/nginx/html/download
cd /usr/local/nginx/html/download
wget http://172.25.28.250/pub/docs/vim.jpg
du -h vim.jpg vim.jpg 444k
nginx -s reload
1、控制单IP并发连接数
在真机进行压力测试,全部通过
ab -c10 -n 10 http://172.25.28.1/download/vim.jpg
Time taken for tests: 0.006 seconds
Complete requests: 10
Failed requests: 0 失败0
在server1主机中设定访问下载链接时,受到控制,重启服务
vim /usr/local/nginx/conf/nginx.conf
#gzip on;
limit_conn_zone $binary_remote_addr zone=addr:10m;
///$binary_remote_addr 表示通过remote_addr这个标识来做限制
///zone=addr:10m 表示生成一个大小为10M,名字为addr的内存区域
server {
listen 80;
server_name localhost;
#charset koi8-r;
#access_log logs/host.access.log main;
location /download/ {
limit_conn addr 1; 限制并发数
limit_req zone=one; 限制带宽
}
location / {
root html;
index index.html index.htm;
}
nginx -s reload
宿主机测试:
ab -c10 -n 10 http://172.25.28.1/download/vim.jpg
Time taken for tests: 0.003 seconds
Complete requests: 10
Failed requests: 2 失败2
2. 限制单位时间内的请求数目,以及速度限制
vim /usr/local/nginx/conf/nginx.conf
#gzip on;
#limit_conn_zone $binary_remote_addr zone=addr:10m;
limit_req_zone $binary_remote_addr zone=one:10m rate=1r/s; (//rate=1r/s表示允许相同标识的客户端的访问频次,这里限制的是每秒1次)
server {
listen 80;
server_name localhost;
#charset koi8-r;
#access_log logs/host.access.log main;
location /download/ {
#limit_conn addr 1;
limit_req zone=one;
}
nginx -s reload
宿主机测试:
ab -c1 -n 10 http://172.25.28.1/download/vim.jpg 设定并发用户数为1,请求总数为10
Time taken for tests: 0.004 seconds
Complete requests: 10
Failed requests: 9
3、排队,超过指定数量则排队访问
在配置文件中设定一次访问5个,超过的排队等待,因为上一个实验设定每秒通过1个请求,则访问2次,差不多10秒。
vim /usr/local/nginx/conf/nginx.conf
location /download/ {
#limit_conn addr 1;
#limit_req zone=one;
limit_req zone=one burst=5;
}
nginx -s reload
宿主机测试:
ab -c1 -n 10 http://172.25.28.1/download/vim.jpg
Time taken for tests: 9.003 seconds
Complete requests: 10
Failed requests: 0
4、无延迟
编辑配置文件,设定请求无延迟,在上一个实验的情况下,只能执行1次,即5个请求,重启服务。
vim /usr/local/nginx/conf/nginx.conf
location /download/ {
#limit_conn addr 1;
#limit_req zone=one;
#limit_req zone=one burst=5;
limit_req zone=one burst=5 nodelay;
}
nginx -s reload
宿主机测试:
ab -c1 -n 10 http://172.25.28.1/download/vim.jpg 只能通过5个,其余被拒绝
Time taken for tests: 0.008 seconds
Complete requests: 10
Failed requests: 4
5. 限制带宽
vim /usr/local/nginx/conf/nginx.conf
location /download/ {
limit_conn addr 1;
#limit_req zone=one;
#limit_req zone=one burst=5;
#limit_req zone=one burst=5 nodelay;
limit_rate 50k;
nginx -s reload
宿主机测试:
ab -c1 -n 5 http://172.25.28.1/download/vim.jpg
Time taken for tests: 40.075 seconds (文件大小444k,限速50k,一个请求大约8s,五个则为40s)
Complete requests: 5
Failed requests: 0
八、nginx配置管理
1. 自动索引
vim /usr/local/nginx/conf/nginx.conf
location /download/ {
limit_conn addr 1;
#limit_req zone=one burst=5 nodelay;
#limit_rate 50k;
autoindex on;
}
nginx -s reload
宿主机浏览器访问:
http://172.25.28.1/download/
显示下载界面
2. nginx expire 缓存配置
缓存可以降低网站带宽,加速用户访问。
编辑配置文件,设定对图片等进行缓存,缓存时间为1年,在此期间访问就会减少访问时间。
vim /usr/local/nginx/conf/nginx.conf
location /download/ {
limit_conn addr 1;
#limit_req zone=one burst=5 nodelay;
#limit_rate 50k;
autoindex on;
} ##在此位置下方进行设定
location ~ .*\.(gif|jpg|png)$ { ##对图片等进行缓存
expires 365d; 缓存时间
root html;
}
nginx -s reload
宿主机测试:
curl -I 172.25.28.1/download/vim.jpg
Expires: Thu, 08 Sep 2022 08:15:03 GMT 缓存时间2022年
3. 日志轮询
编写一个脚本,设定打开nginx时会生成日志文件,命名格式为前一天。
cd /opt/ ##第三方软件安装位置
vim nginx.sh
#!/bin/bash
cd /usr/local/nginx/logs && mv access.log access_$(date +%F -d -1day).log
kill -USR1 `cat /usr/local/nginx/logs/nginx.pid`
chmod +x nginx.sh 给脚本执行权限
./nginx.sh 执行脚本
cd /usr/local/nginx/logs/ 切入到日志目录
ls --> access_2021-08-31.log 生成日志
4、禁用不必要的日志记录,以节省磁盘IO的消耗
在配置文件中设定浏览器访问指定目录时禁用生成日志文件。
vim /usr/local/nginx/conf/nginx.conf
location ~ .*\.(gif|jpg|png)$ { ##对图片等进行缓存
expires 365d; 缓存时间
root html;
} 这个位置的下面加入设定
location /status {
stub_status on;
access_log off;
}
nginx -s reload
此时宿主机浏览器访问http://172.25.28.1/status/目录,在日志目录中不会生成日志记录。但当在真机中使用curl -I 172.25.28.1/status命令访问该目录时,会产生日志文件。
cat /usr/local/nginx/logs/access.log
5. 站点目录和文件的限制
在配置文件中设定指定目录只能本机访问,拒绝其他所有请求。
vim /usr/local/nginx/conf/nginx.conf
location /status {
stub_status on;
access_log off;
allow 127.0.0.1;
deny all;
}
nginx -s reload
测试:
当在真机访问status目录时,拒绝访问,报错403,资源不可用,服务器理解客户的请求,但拒绝处理。
当在server1本机访问时,允许访问。
curl localhost/status
6. 中文乱码
nginx默认不支持中文字符,在浏览器访问时,中文会变成乱码。
vim /usr/local/nginx/html/index.html
1111 哈哈
宿主机浏览器测试:
http://172.25.28.1/
1111 ä½ å¥½
解决方法:
vim /usr/local/nginx/conf/nginx.conf
server {
listen 80;
server_name localhost;
charset utf-8; 正常显示中文
#charset koi8-r;
nginx -s reload
此时宿主机浏览器再次测试,中文正常显示
九、nginx 重定向
1. 防止域名恶意解析到服务器IP
1)拒绝访问,报错500
vim /usr/local/nginx/conf/nginx.conf
server {
listen 80;
server_name localhost;
return 500;
nginx -s reload
curl -I localhost ##HTTP/1.1 500 Internal Server Error
宿主机浏览器访问172.25.28.1也是报错500
2)将所有访问重定向至指定域名
vim /usr/local/nginx/conf/nginx.conf
server {
listen 80;
server_name localhost;
rewrite ^(.*) http://www.baidu.com permanent; 重定向
nginx -s reload
curl -I localhost ##Location: http://www.baidu.com
宿主机浏览器访问172.25.28.1,自动跳转至http://www.baidu.com
2. 端口重定向
由于443是 https 使用,所以先制作一个加密证书,并移动到配置目录中,编辑配置文件,将80端口定向到443端口,检测语法,重启服务,查询端口
cd /etc/pki/tls/certs/
make cert.pem
mv cert.pem /usr/local/nginx/conf/
vim /usr/local/nginx/conf/nginx.conf
server {
listen 443 ssl;
server_name www.tao.com;
ssl_certificate cert.pem;
ssl_certificate_key cert.pem;
ssl_session_cache shared:SSL:1m;
ssl_session_timeout 5m;
ssl_ciphers HIGH:!aNULL:!MD5;
ssl_prefer_server_ciphers on;
server {
listen 80;
server_name www.tao.com;
rewrite ^/(.*)$ https://www.tao.com/$1 permanent;
#location / {
# proxy_pass http://tom/;
#}
}
nginx -s reload
netstat -antlup |grep 443 查看443端口开启成功
测试:
server1:
curl -I www.tao.com
Location: https://www.tao.com/
宿主机浏览器访问http://www.tao.com/自动跳转到https://www.tao.com/
3. 虚拟主机重定向
1)www.tao.com 重定向bbs.tao.com
mkdir /bbs
vim /usr/local/nginx/conf/nginx.conf
server {
listen 80;
server_name www.tao.com;
rewrite ^/bbs$ http://bbs.tao.com permanent; ##^/bbs$表示匹配以/开头,bbs结尾,,比如www.tao.com/bbs,如果后加其他url,则不能重定向
rewrite ^/(.*)$ http://bbs.tao.com/$1 permanent; ##^/(.*)$表示匹配以/开头,$结尾,后面可以加url,比如www.tao.com/bbs/bbs.html
#rewrite ^/(.*)$ https://www.tao.com/$1 permanent;
#location / {
# proxy_pass http://tom/;
#}
}
server {
listen 80;
server_name bbs.tao.com;
location / {
root /bbs;
index index.html;
}
}
nginx -s reload
测试:
server1
curl -I www.tao.com/bbs
Location: http://bbs.tao.com
宿主机浏览器访问www.tao.com/bbs直接跳转到http://bbs.tao.com
2)bbs.tao.com 重定向www.tao.com
vim /usr/local/nginx/conf/nginx.conf
server {
listen 80;
server_name www.tao.com bbs.tao.com;
#rewrite ^/bbs$ http://bbs.tao.com permanent;
#rewrite ^/(.*)$ http://bbs.tao.com/$1 permanent;
#rewrite ^/(.*)$ https://www.tao.com/$1 permanent;
#location / {
# proxy_pass http://tom/;
#}
if ($host = "bbs.tao.com") {
rewrite ^/(.*)$ http://www.tao.com/bbs/$1 permanent;
}
location / {
root /www;
index index.html;
proxy_pass http://tom;
}
}
#server {
# listen 80;
# server_name bbs.tao.com;
#
# location / {
# root /bbs;
# index index.html;
# }
#}
nginx -s reload
测试:
宿主机
vim /etc/hosts
172.25.28.1 server1 www.tao.com bbs.tao.com
浏览器访问http://bbs.tao.com会自动跳转到http://www.tao.com/bbs/
十、防盗链
1. server2盗取server1的图片
在server2中编辑一发布文件,写入访问该文件时,盗取server1主机中的某一图片。
server2:
cd /usr/local/nginx/html
vim test.html ##盗链文件,盗取server1主机的图片
<html>
<body>
<img src = "http://www.tao.com/download/vim.jpg">
</body>
</html>
nginx -s reload
此时在宿主机浏览器中可以直接访问server1的图片,也可以也可以通过访问server2,访问到server1主机的图片。
172.25.28.1/download/vim.jpg <====>172.25.28.2/test.html
2. 设定防盗链
在server1的配置文件中设定当被访问时,返回403报错或者显示指定防盗链图片,重启服务。
vim /usr/local/nginx/conf/nginx.conf
server {
listen 80;
server_name www.tao.com;
location ~ \.(jpg|png)$ {
valid_referers none blocked www.tao.com;
if ($invalid_referer) {
#return 403; 二选一
rewrite ^/ http://172.25.28.2/daolian.jpg; 二选一
}
}
nginx -s reload
宿主机浏览器访问http://172.25.28.2/test.html将不再显示vim.jpg,显示制定链接内容