一、Nginx概述
介绍
官方网站:nginx
Nginx是一款轻量级的Web 服务器/反向代理服务器及电子邮件(IMAP/POP3)代理服务器,并在一个BSD-like 协议下发行。其特点是占有内存少,并发能力强,事实上nginx的并发能力确实在同类型的Web服务器中表现较好。
功能
- 基本 HTTP 服务器功能
- 其他HTTP服务器功能
- 邮件代理服务器功能
- TCP/UDP代理服务器功能
Nginx服务
作为 Web 服务器:相比 Apache,Nginx 占用更少的资源,支持更多的并发连接,体现更高的效率,这点使 Nginx 尤其受到虚拟主机提供商的欢迎。能够支持高达 50,000 个并发连接数的响应。
作为负载均衡服务器:Nginx 既可以在内部直接支持 Rails 和 PHP,也可以支持作为 HTTP代理服务器 对外进行服务。Nginx 用 C 编写, 不论是系统资源开销还是 CPU 使用效率都比 Perl要好的多。
作为邮件代理服务器: Nginx 同时也是一个非常优秀的邮件代理服务器(最早开发这个产品的目的之一也是作为邮件代理服务器),Last.fm 描述了成功并且美妙的使用经验。
Nginx 安装非常的简单,配置文件 非常简洁(还能够支持perl语法),Bugs非常少的服务器: Nginx 启动特别容易,并且几乎可以做到7*24不间断运行,即使运行数个月也不需要重新启动。你还能够在不间断服务的情况下进行软件版本的热升级。
IO多路复用
IO多路复用基本概念
IO多路复用是一种并发编程技术,它允许一个或多个事件循环同时处理多个I/O操作。这种技术通过监视多个文件描述符(如socket)的状态,来同时管理多个I/O流。当某个文件描述符就绪(如可读、可写或有异常),系统就会通知相应的程序进行相应的读写操作。
Nginx中IO多路复用的实现
Nginx在实现IO多路复用时,主要采用了以下几种机制
非阻塞I/O
Nginx使用非阻塞I/O来处理并发连接。当一个连接建立时,Nginx会立即开始监听该连接上的事件,而不会等待数据传输完成。这样,Nginx就可以同时处理多个连接,而不会因等待某个连接的数据传输完成而阻塞。
事件循环
事件循环是IO多路复用的核心。Nginx通过一个线程(或少量线程)来处理事件循环中的事件。当事件循环中没有待处理的事件时,线程会休眠,等待新的事件产生。一旦有新的事件产生,线程就会根据事件的类型执行相应的回调函数。
回调机制
Nginx通过回调机制来实现IO多路复用。当一个事件被触发时(如连接建立、数据可读、可写或有异常),Nginx会调用相应的回调函数来处理该事件。这些回调函数通常是由Nginx的插件或模块实现的,它们会根据不同的I/O类型来执行相应的操作。
epoll
在Linux系统中,Nginx主要使用epoll作为其IO多路复用的实现方式。epoll是select和poll的增强版本,具有更高的效率和更好的扩展性。它使用一种高效的机制来管理大量的文件描述符,并能够在有I/O事件发生时及时通知进程。
Nginx中IO多路复用的优势
高性能
通过非阻塞I/O和事件循环,Nginx能够快速响应客户端的请求,提高处理效率。同时,epoll等高效的IO多路复用机制也进一步提升了Nginx的性能。
高可靠性
Nginx采用了事件驱动的编程模型,具有很高的容错能力。它能够在发生错误或异常时自动处理,并恢复正常的服务。
高可扩展性
Nginx支持通过插件或模块来扩展其功能,并通过回调机制来处理各种I/O事件。这使得Nginx能够灵活地应对不同的应用场景和需求。
Nginx中IO多路复用的应用场景
Nginx的IO多路复用技术广泛应用于Web服务器、反向代理服务器、负载均衡器等场景。在这些场景中,Nginx需要同时处理大量的并发连接和请求,而IO多路复用技术正是实现这一目标的关键。
二、安装Nginx
yum安装
nginx的官方网站:nginx news
这里安装nginx稳定版本
1.编辑nginx.repo
vim /etc/yum.repos.d/nginx.repo
[nginx-stable]
name=nginx stable repo
baseurl=http://nginx.org/packages/centos/$releasever/$basearch/
gpgcheck=1
enabled=1
gpgkey=https://nginx.org/keys/nginx_signing.key
module_hotfixes=true
[nginx-mainline]
name=nginx mainline repo
baseurl=http://nginx.org/packages/mainline/centos/$releasever/$basearch/
gpgcheck=1
enabled=0
gpgkey=https://nginx.org/keys/nginx_signing.key
module_hotfixes=true
2.安装
yum-config-manager --enable nginx-mainline
yum install nginx
具体详细操作步骤:nginx: Linux packages
文件目录
/etc/nginx/nginx.conf
/etc/nginx/conf.d/default.conf
/var/log/nginx/access.log
/var/log/nginx/error.log
/usr/share/nginx/html
编译安装
- 安装编译 Nginx 依赖包(创建编译环境)
yum -y install gcc gcc-c++ make zlib-devel pcre pcre-devel openssl-devel perl-devel perl-ExtUtils-Embed gd-devel
- 下载安装包
wget http://nginx.org/download/nginx-1.26.0.tar.gz
- 创建用户
useradd -s /sbin/nologin -M nginx
- 解压编译
tar zxvf nginx-1.26.0.tar.gz -C /usr/local/
/usr/local/nginx-1.26.0/目录下执行:
./configure \
--user=nginx \
--group=nginx \
--prefix=/usr/local/nginx \
--conf-path=/etc/nginx/nginx.conf \
--sbin-path=/usr/sbin/nginx \
--error-log-path=/var/log/nginx/nginx_error.log \
--http-log-path=/var/log/nginx/nginx_access.log \
--pid-path=/usr/local/nginx/run/nginx.pid
- 安装
/usr/local/nginx-1.26.0/目录下执行:
make && make install
- 系统添加nginx服务
vim /usr/lib/systemd/system/nginx.service
添加:
[Unit]
Description=nginx
After=network.target
[Service]
Type=forking
ExecStart=/usr/sbin/nginx
ExecReload=/usr/sbin/nginx -s reload
ExecStop=/usr/sbin/nginx -s quit
PrivateTmp=true
[Install]
WantedBy=multi-user.target
tips:
[Unit]:服务的说明
Description:描述服务
After:描述服务类别
[Service]服务运行参数的设置
Type=forking是后台运行的形式
ExecStart为服务的具体运行命令
ExecReload为重启命令
ExecStop为停止命令
PrivateTmp=True表示给服务分配独立的临时空间
注意:[Service]的启动、重启、停止命令全部要求使用绝对路径
[Install]运行级别下服务安装的相关设置,可设置为多用户,即系统运行级别为3
- 启动nginx
pkill nginx
systemctl daemon-reload
systemctl start nginx
Nginx指令
nginx -V # 查看Nginx版本号
nginx -h # nginx帮助命令
nginx -t # 验证配置语法是否正确
nginx -s reload # 配置文件修改重装载命令
start nginx # 启动nginx
nginx # 启动nginx
nginx -s stop # 块速停止或关闭nginx
nginx -s quit # 正常停止或关闭(会等到worker处理完成请求后关闭)
tips:
注意windows下需要将nginx.exe加入环境变量,然后才能执行上面的命令。不要双击启动,不然只能从任务列表中删除
三、Nginx配置文件模块解析
概念
Nginx的默认配置文件是nginx.conf,子配置文件conf.d/default.conf
Nginx的配置文件是一个文本文件。它使用一种简洁而灵活的语法来定义Nginx服务器的行为和功能。配置文件中的指令按照特定的顺序进行解析和执行,从而实现对服务器行为的精确控制。
配置文件结构
配置文件结构
全局块
|——events块
|——http块
|——server块
|——location块
配置文件的指令
listen 指定Nginx服务器监听的端口
server_name 指定虚拟主机的域名或IP地址
root 指定网站的根目录
index 指定默认的首页文件
location 指定URL路径的匹配规则和处理方式
proxy_pass 配置反向代理服务器的目标地址
rewrite 配置URL重写规则
user 指定Nginx worker进程运行的用户
worker_processes 指定Nginx启动的worker进程数
error_log 指定错误日志的路径
pid 指定进程ID文件的路径
events 配置事件模块,如worker连接数
http 配置HTTP模块
include 包含其他配置文件
server 定义一个虚拟主机。
配置文件结构模块中常用命令
全局块
user worker_processe error_log pid events http
events块
worker_connections
http块
server include default_type log_format main access_log
sendfile keepalive_timeout gzip include tcp_nopush
server块
location listen server_name
location块
root index rewrite proxy_pass
location模块详解
概念
location模块在server模块中根据不同的url处理不同的请求
location处理是按照从上到下的顺序依次处理
语法
location [=|~|~*|^~|@] [匹配模式] {
...
}
匹配方式
= 表示精确匹配,优先级也是最高的
^~ 表示url以某个常规字符串开头,理解为匹配url路径即可
~ 表示区分大小写的正则匹配
~* 表示不区分大小写的正则匹配
!~ 表示区分大小写不匹配的正则
!~* 表示不区分大小写不匹配的正则
/ 通用匹配,任何请求都会匹配到
#优先级
= > ~|~*|!~|!~* > /
ROOT和Alias的区别
区别:
location [uri]{
...
}
root /[发布目录]
alias /[发布目录]
访问uri时,使用root寻找资源的时候是/[发布目录]/[uri]
访问uri时,使用alias寻找资源的时候是/[发布目录]
示例:
1.编辑文件
vim /etc/nginx/conf.d/root_alias.conf
server {
listen 80;
server_name localhost;
location /log1 {
root /usr/share/nginx/html;
index index.html index.htm;
}
location /log {
alias /usr/share/nginx/html/log2;
index index.html index.htm;
}
}
2.创建目录
mkdir -p /usr/share/nginx/html/log1
mkdir -p /usr/share/nginx/html/log2
vim /usr/share/nginx/html/log1/index.html
vim /usr/share/nginx/html/log2/index.html
3.重载配置文件
nginx -t
systemctl reload nginx
systemctl restart nginx
四、Nginx虚拟主机
虚拟主机概念
虚拟主机是一种特殊的软硬件技术,它可以将网络上的每一台计算机分成多个虚拟主机,每个虚拟主机可以独立对外提供web服务,这样就可以实现一台主机对外提供多个web服务,每个虚拟主机之间是独立的,互不影响。
Nginx虚拟主机配置
前提:yum安装的nginx
主机:192.168.252.148
基于域名的虚拟主机
1.编辑虚拟主机
vim /etc/nginx/conf.d/default.conf ---[1]
或
vim /etc/nginx/nginx.conf ---[2]
添加内容:
[1]
server {
listen 80;
server_name www.xq.com; #添加域名
location / {
root /www/nginx;
index index.html;
}
}
[2]
http{
...
server{
listen 80;
server_name www.xq.com; #添加域名
location / {
root /www/nginx;
index index.html;
}
}
...
}
2.在发布目录中添加寻找的资源
vim /www/nginx/index.html
添加html代码
3.重载配置文件
systemctl reload nginx
systemctl restart nginx
4.添加linux端的hosts
vim /etc/hosts
192.168.252.148 www.xq.com
5.windos的hosts文件进行添加域名解析
打开C:\Windows\System32\drivers\etc\hosts
添加
192.168.252.148 www.xq.com
6.重载配置文件
nginx -t
systemctl reload nginx
systemctl restart nginx
基于ip的虚拟主机
1.添加临时虚拟网络(需要与本机网段一致)
ip a add dev ens33 192.168.252.200/24
2.修改配置文件
vim /etc/nginx/conf.d/default.conf ---[1]
或
vim /etc/nginx/nginx.conf ---[2]
添加内容:
[1]
server {
listen 80;
server_name 192.168.252.200; #修改ip地址
location / {
root /www/nginx;
index index.html;
}
}
[2]
http{
...
server{
listen 80;
server_name 192.168.252.200; #修改ip地址
location / {
root /www/nginx;
index index.html;
}
}
...
}
3.在发布目录中添加寻找的资源
vim /www/nginx/index.html
添加html代码
4.重载配置文件
nginx -t
systemctl reload nginx
systemctl restart nginx
基于端口号的虚拟主机
1.修改配置文件
vim /etc/nginx/conf.d/default.conf ---[1]
或
vim /etc/nginx/nginx.conf ---[2]
添加内容:
[1]
server {
listen 81; #修改端口号
server_name 192.168.252.200;
location / {
root /www/nginx;
index index.html;
}
}
[2]
http{
...
server{
listen 81; #修改ip地址
server_name 192.168.252.200;
location / {
root /www/nginx;
index index.html;
}
}
...
}
2.在发布目录中添加寻找的资源
vim /www/nginx/index.html
添加html代码
3.重载配置文件
nginx -t
systemctl reload nginx
systemctl restart nginx
虚拟配置模版
添加server模块的模版
server {
listen [监听的端口号];
server_name [ip地址/域名];
location / {
root [发布目录路径];
index [在发布目录寻找的资源文件];
}
}
Nginx显示文件夹结构
示例
节点:192.168.252.149
1.修改配置文件
vim /etc/nginx/conf.d/default.conf ---[1]
或
vim /etc/nginx/nginx.conf ---[2]
添加模块
server {
listen 82
server_name 192.168.252.149
location / {
root /data/www/file; #显示目录
autoindex on;
autoindex_exact_size off;
autoindex_localtime on;
}
}
2.创建发布目录
mkdir -p /data/www/file
3.重载配置文件
nginx -t
systemctl reload nginx
systemctl restart nginx
五、Nginx功能
Nginx变量
简介
所有的 Nginx变量在 Nginx 配置文件中引用时都须带上 $ 前缀
在 Nginx 配置中,只存字符串类型
nginx有两种变量类型——自定义变量与内置预定义变量
自定义变量
语法格式
set $[变量名] [变量值]
作用域:
sever,http,location
tips:
nginx中定义的变量必须都以$开头 引用的时候必须有$
nginx的配置文件中所有使用的变量都必须是声明过的,否则nginx会无法启动并打印相关异常日志
nginx的变量的声明在其子模块也会生效
示例
nginx 1.26.2
安装模块
1.安装git
yum -y install epel*
yum -y install git
2.下载与你版本呢对应版本的nginx源码包
wget https://nginx.org/download/nginx-1.26.2.tar.gz
tar -xzf nginx-1.26.2.tar.gz -C /usr/local
3.git到echo-nginx-module
git clone https://github.com/openresty/echo-nginx-module.git
mv echo-nginx-module /usr/local
4.预编译(使用nginx -V命令进行查看编译的路径然后再最后添加--add-module=/usr/local/echo-nginx-module即可)
yum:
cd /usr/local/nginx-1.26.2
./configure --prefix=/etc/nginx --sbin-path=/usr/sbin/nginx --modules-path=/usr/lib64/nginx/modules --conf-path=/etc/nginx/nginx.conf --error-log-path=/var/log/nginx/error.log --http-log-path=/var/log/nginx/access.log --pid-path=/var/run/nginx.pid --lock-path=/var/run/nginx.lock --http-client-body-temp-path=/var/cache/nginx/client_temp --http-proxy-temp-path=/var/cache/nginx/proxy_temp --http-fastcgi-temp-path=/var/cache/nginx/fastcgi_temp --http-uwsgi-temp-path=/var/cache/nginx/uwsgi_temp --http-scgi-temp-path=/var/cache/nginx/scgi_temp --user=nginx --group=nginx --with-compat --with-file-aio --with-threads --with-http_addition_module --with-http_auth_request_module --with-http_dav_module --with-http_flv_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_mp4_module --with-http_random_index_module --with-http_realip_module --with-http_secure_link_module --with-http_slice_module --with-http_ssl_module --with-http_stub_status_module --with-http_sub_module --with-http_v2_module --with-mail --with-mail_ssl_module --with-stream --with-stream_realip_module --with-stream_ssl_module --with-stream_ssl_preread_module --with-cc-opt='-O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector-strong --param=ssp-buffer-size=4 -grecord-gcc-switches -m64 -mtune=generic -fPIC' --with-ld-opt='-Wl,-z,relro -Wl,-z,now -pie' --add-module=/usr/local/echo-nginx-module
5.编译
make
6.移动命令
mv /usr/sbin/ngin /usr/bin/nginx_bak
cp objs/nginx /usr/sbin/
7.启动
/usr/sbin/nginx
yum安装
编辑配置文件:
vim /etc/nginx/conf.d/echo.conf
server {
listen 81;
server_name localhost;
location / {
set $hello hello;
echo $hello;
echo ${hello};
echo "$hello world"
}
location /no {
echo "hello=[$hello]"
}
}
2.重启
nginx -t
systemctl reload nginx
systemctl restart nginx
3.访问
curl http://192.168.252.149:81
内置预定义变量
内置预定义变量可以直接引用
参数列表
变量名 | 定义 |
$arg_PARAMETER | GET请求中变量名PARAMETER参数的值。 |
$args | 这个变量等于GET请求中的参数。例如,foo=123&bar=blahblah;这个变量只可以被修改 |
$binary_remote_addr | 二进制码形式的客户端地址。 |
$body_bytes_sent | 传送页面的字节数 |
$content_length | 请求头中的Content-length字段。 |
$content_type | 请求头中的Content-Type字段。 |
$cookie_COOKIE | cookie COOKIE的值。 |
$document_root | 当前请求在root指令中指定的值。 |
$document_uri | 与$uri相同。 |
$host | 请求中的主机头(Host)字段,如果请求中的主机头不可用或者空,则为处理请求的server名称(处理请求的server的server_name指令的值)。值为小写,不包含端口。 |
$hostname | 机器名使用 gethostname系统调用的值 |
$http_HEADER | HTTP请求头中的内容,HEADER为HTTP请求中的内容转为小写,-变为_(破折号变为下划线),例如:$http_user_agent(Uaer-Agent的值); |
$sent_http_HEADER | HTTP响应头中的内容,HEADER为HTTP响应中的内容转为小写,-变为_(破折号变为下划线),例如: $sent_http_cache_control, $sent_http_content_type…; |
$is_args | 如果$args设置,值为"?",否则为""。 |
$limit_rate | 这个变量可以限制连接速率。 |
$nginx_version | 当前运行的nginx版本号。 |
$query_string | 与$args相同。 |
$remote_addr | 客户端的IP地址。 |
$remote_port | 客户端的端口。 |
$remote_user | 已经经过Auth Basic Module验证的用户名。 |
$request_filename | 当前连接请求的文件路径,由root或alias指令与URI请求生成。 |
$request_body | 这个变量(0.7.58+)包含请求的主要信息。在使用proxy_pass或fastcgi_pass指令的location中比较有意义。 |
$request_body_file | 客户端请求主体信息的临时文件名。 |
$request_completion | 如果请求成功,设为"OK";如果请求未完成或者不是一系列请求中最后一部分则设为空。 |
$request_method | 这个变量是客户端请求的动作,通常为GET或POST。包括0.8.20及之前的版本中,这个变量总为main request中的动作,如果当前请求是一个子请求,并不使用这个当前请求的动作。 |
$request_uri | 这个变量等于包含一些客户端请求参数的原始URI,它无法修改,请查看$uri更改或重写URI。 |
$scheme | 所用的协议,比如http或者是https,比如rewrite ^(.+)$ $scheme://example.com$1 redirect; |
$server_addr | 服务器地址,在完成一次系统调用后可以确定这个值,如果要绕开系统调用,则必须在listen中指定地址并且使用bind参数。 |
$server_name | 服务器名称。 |
$server_port | 请求到达服务器的端口号。 |
$server_protocol | 请求使用的协议,通常是HTTP/1.0或HTTP/1.1。 |
$uri | 请求中的当前URI(不带请求参数,参数位于args,不同于浏览器传递的args),不同于浏览器传递的request_uri的值,它可以通过内部重定向,或者使用index指令进行修改。不包括协议和主机名,例如/foo/bar.html |
示例
uri 和 request_uri
1.编辑配置文件
vim /etc/nginx/conf.d/uri_request_uri.conf
配置文件:
server {
listen 80;
server_name localhost;
location /uri_request {
echo "usi = $uri";
echo "request_uri = $request_uri";
}
}
2.重启
systemctl restart nginx
3.访问
curl http://192.168.252.149/uri_request?a=3
curl http://192.168.252.149/uri_request
curl http://192.168.252.149/uri_request/hello%20world?a=3&b=4
$arg_[参数]
参数不区分大小写
1.编辑配置文件
vim /etc/nginx/conf.d/args.conf
server {
listen 80;
server_name localhost;
location /test-arg {
echo "name: $arg_name";
echo "class: $arg_class";
}
}
2.重启
systemctl restart nginx
3.访问
curl http://192.168.252.149/args
curl http://192.168.252.149/args?name=Tom&class=3
curl http://192.168.252.149/args?Name=Jimmy&class=DSfef
Nginx Proxy 代理
代理原理
代理实际上指的就是代理服务器,英文叫作proxy server,它的功能是代理网络用户去取得网络信息。形象地说,它是网络信息的中转站。在我们正常请求一个网站时,是发送了请求给Web服务器,Web服务器把响应传回给我们。如果设置了代理服务器,实际上就是在本机和服务器之间搭建了一个桥,此时本机不是直接向Web服务器发起请求,而是向代理服务器发出请求,请求会发送给代理服务器,然后由代理服务器再发送给Web服务器,接着由代理服务器再把Web服务器返回的响应转发给本机。这样我们同样可以正常访问网页,但这个过程中Web服务器识别出的真实IP就不再是我们本机的IP了,就成功实现了IP伪装,这就是代理的基本原理。
反向代理
反向代理的过程隐藏了真实的服务器,客户不知道真正提供服务的机器是哪台,客户端请求的服务都被代理服务器处理。反向代理代理的是响应方,也就是服务端;我们请求www.baidu.com时,这www.baidu.com就是反向代理服务器,真实提供服务的服务器有很多台,反向代理服务器会把我们的请求分/转发到真实提供服务的各台服务器。Nginx就是性能非常好的反向代理服务器,用来做负载均衡。
正向代理
正向代理的过程隐藏了真实的请求客户端,服务器不知道真实的客户端是谁,客户端请求的服务都被代理服务器代替请求。我们常说的代理也就是正向代理,正向代理代理的是请求方,也就是客户端;比如我们要访问youtube,可是不能访问,只能先安装个FQ软件代你去访问,通过FQ软件才能访问,FQ软件就叫作正向代理。
Nginx Proxy配置
代理配置参数
代理
Syntax: proxy_pass URL; #代理的后端服务器URL
Default: —
Context: location, if in location, limit_except
头信息
Syntax: proxy_set_header field value;
Default: proxy_set_header Host $proxy_host; #设置真实客户端地址
proxy_set_header Connection close;
Context: http, server, location
超时
Syntax: proxy_connect_timeout time;
Default: proxy_connect_timeout 60s; #链接超时
Context: http, server, location
Syntax: proxy_read_timeout time;
Default: proxy_read_timeout 60s;
Context: http, server, location
Syntax: proxy_send_timeout time; #nginx进程向fastcgi进程发送request的整个过程的超时时间
Default: proxy_send_timeout 60s;
Context: http, server, location
准备
192.168.252.147 代理
192.168.252.148 服务端
启用代理
192.168.252.147 :
1.编辑配置文件
vim /etc/nginx/conf.d/default.conf ---[1]
或
vim /etc/nginx/nginx.conf ---[2]
server{
listen 80
server_name localhost;
location / {
proxy_pass http://192.168.252.148:80;
}
}
2.重载配置文件
nginx -t
systemctl reload nginx
systemctl restart nginx
192.168.252.148:
服务端配置虚拟主机和发布目录同上的虚拟主机配置
查看日志
tail -f /var/log/
配置模版
代理端配置:
server {
listen [监听的端口号];
server_name [ip地址/域名];
location / {
proxy_pass http://[需要跳转的ip地址/域名]:[端口号];
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_connect_timeout 30;
proxy_send_timeout 60;
proxy_read_timeout 60;
}
}
tips:
参数解释
proxy_pass # 跳转真实服务器的地址,可以是ip也可以是域名和url地址
proxy_set_header # 重新定义或者添加发往后端服务器的请求头
proxy_set_header X-Real-IP # 启用客户端真实地址(否则日志中显示的是代理在访问网站)
proxy_set_header X-Forwarded-For # 记录代理地址
proxy_connect_timeout # 后端服务器连接的超时时间发起三次握手等候响应超时时间
proxy_send_timeout # 后端服务器数据回传时间,就是在规定时间之内后端服务器必须传完所有的数据
proxy_read_timeout # nginx接收upstream(上游/真实) server数据超时, 默认60s, 如果连续的60s内没有收到1个字节, 连接关闭。像长连接
Nginx负载均衡
准备环境
192.168.252.147 代理
192.168.252.148 服务端
192.168.252.149 服务端
代理端配置
192.168.252.147:
1.编辑配置文件
vim /etc/nginx/conf.d/default.conf ---[1]
或
vim /etc/nginx/nginx.conf ---[2]
添加模块
upstream web {
server 192.168.252.148:8080;
server 192.168.252.149:8080;
}
server {
listen 80;
server_name localhost;
location / {
proxy_pass http://web;
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_connect_timeout 30;
proxy_send_timeout 60;
proxy_read_timeout 60;
}
}
2.检查配置文件并重启
nginx -t
systemctl reload nginx
systemctl restart nginx
192.168.252.148:
配置虚拟主机
tips:
负载均衡配置状态参数
down 表示当前的server暂时不参与负载均衡。
backup 预留的备份机器。当其他所有的非backup机器出现故障或者忙的时候,才会请求backup机器,因此这台机器的压力最轻。
max_fails 允许请求失败的最大次数,默认为1。当超过最大次数时,返回错误。
fail_timeout 在经历了max_fails次失败后,暂停服务的时间单位秒。max_fails可以和fail_timeout一起使用。
例子:
upstream web {
server 192.168.252.148:8080 max_fails=2 fail_timeout=2 ;
server 192.168.252.149:8080 max_fails=2 fail_timeout=1 down;
}
配置负载均衡算法
算法:
- 轮循环(默认):ABABAB...
- 热备:A挂了,B才会启用
- 加权轮询:根据权重分配AB的启用顺序
- ip_hash :当你访问A的时候,就会固定访问A不会变到B
- url_hash:按访问url的结果来分配请求
- fair:看A和B的加载时长和页面大小来进行负载均衡(不常用不在下面做模版)
模版:
1.轮询
upstream [地址池名] {
server [ip地址]:[端口];
server [ip地址]:[端口];
...
}
2.热备
upstream [地址池名] {
server [ip地址]:[端口];
server [ip地址]:[端口] backup;
...
}
3.加权轮询
upstream [地址池名] {
server [ip地址]:[端口] weight=[权重];
server [ip地址]:[端口] weight=[权重];
...
}
4.ip_hash
upstream [地址池名] {
ip_bash;
server [ip地址]:[端口];
server [ip地址]:[端口];
...
}
Nginx实现动静分离
NginxPHP动静分离
准备环境
192.168.252.147 代理
192.168.252.148 静态资源服务端
192.168.252.149 动态资源服务端
配置代理
192.168.252.147:
1.编辑配置文件
vim /etc/nginx/conf.d/upstream.conf
配置文件:
upstream static {
server 192.168.252.148:83 weight=1 max_fails=1 fail_timeout=60s;
}
upstream dynamic {
server 192.168.252.149:83 weight=1 max_fails=1 fail_timeout=60s;
}
server {
listen 83;
server_name localhost;
location ~ .*\.(html|gif|jpg|png|bmp|swf|css|js)$ {
proxy_pass http://static;
proxy_set_header Host $host:$server_port;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
location ~ .*\.(php|jsp)$ {
proxy_pass http://dynamic;
proxy_set_header Host $host:$server_port;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
2.重启
nginx -t
systemctl reload nginx
systemctl restart nginx
配置静态资源服务端
192.168.252.148:
1.编辑配置文件
vim /etc/nginx/conf.d/upstream.conf
配置文件:
server {
listen 83;
server_name localhost;
location ~ .*\.(html|gif|jpg|png|bmp|swf|css|js)$ {
root /upstream/nginx/html/;
index index.html index.htm;
}
}
2.创建发布目录和文件
mkdir -p /upstream/nginx/html/
vim /upstream/nginx/html/index.html
3.重启
nginx -t
systemctl reload nginx
systemctl restart nginx
配置静态资源服务端
用php做后端动态资源
1.准备php
rpm -Uvh https://mirror.webtatic.com/yum/el7/webtatic-release.rpm
rpm -Uvh https://mirror.webtatic.com/yum/el7/epel-release.rpm
yum install php71w-xsl php71w php71w-ldap php71w-cli php71w-common php71w-devel php71w-gd php71w-pdo php71w-mysql php71w-mbstring php71w-bcmath php71w-mcrypt php71w-fpm -y
systemctl start php-fpm
systemctl enable php-fpm
2.编辑配置文件
vim /etc/nginx/conf.d/upstream.conf
配置文件:
server {
listen 83;
server_name localhost;
location ~ \.(php|jsp)$ {
root /upstream/nginx/html/;
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
}
3.创建发布目录和文件
mkdir -p /upstream/nginx/html/
vim /upstream/nginx/html/index.php
<?php
phpinfo();
?>
4.重启
nginx -t
systemctl reload nginx
systemctl restart nginx
测试
NginxTomcat进行动静分离
准备环境
192.168.252.147 代理
192.168.252.148 静态资源服务端
192.168.252.149 动态资源服务端
配置代理
192.168.252.147:
1.配置代理
vim /etc/nginx/conf.d/tomcatsd.conf
配置文件:
upstream static1 {
server 192.168.252.148:85 weight=1 max_fails=1 fail_timeout=60s;
}
upstream dynamic1 {
server 192.168.252.149:8080 weight=1 max_fails=1 fail_timeout=60s;
}
server {
listen 85;
server_name localhost;
location ~ .*\.(html|gif|jpg|png|bmp|swf|css|js)$ {
proxy_pass http://static1;
proxy_set_header Host $host:$server_port;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
location ~ .*\.(php|jsp|svg|png|gif|css|ico|txt)$ {
proxy_pass http://dynamic1;
proxy_set_header Host $host:$server_port;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
2.重启
nginx -t
systemctl reload nginx
systemctl restart nginx
配置静态资源服务端
192.168.252.147:
1.编辑配置文件:
vim /etc/nginx/conf.d/tomcatstatic.conf
配置文件:
server {
listen 85;
server_name localhost;
location ~ .*\.(html|gif|jpg|png|bmp|swf|css|js)$ {
root /static/html;
index index.html;
}
}
2.创建发布目录和发布文件
mkdir -p /static/html
vim /static/html/index.html
3.重启
nginx -t
systemctl reload nginx
systemctl restart nginx
配置动态资源端
动态资源环境准备
1.安装jdk
wget https://download.oracle.com/otn/java/jdk/8u411-b09/43d62d619be4e416215729597d70b8ac/jdk-8u411-linux-x64.tar.gz
tar -xvzf jdk-8u411-linux-x64.tar.gz -C /usr/local/
cd /usr/local/
mv jdk1.8.0_411/ java
vim /etc/profile
export JAVA_HOME=/usr/local/java
export PATH=$JAVA_HOME/bin:$JAVA_HOME/jre/bin:$PATH
source /etc/profile
2.安装tomcat
wget https://archive.apache.org/dist/tomcat/tomcat-8/v8.5.45/bin/apache-tomcat-8.5.45.zip
tar -xvzf apache-tomcat-8.5.45.zip -C /usr/local
cd /usr/local
mv apache-tomcat-8.5.45/ tomcat
ln -s /usr/local/tomcat/bin/startup.sh /root/tomcat_start.sh
./tomcat_start.sh
进入tomcat的发布目录
cd /usr/local/tomcat/webapps/ROOT
ls
asf-logo-wide.svg bg-nav.png index.jsp tomcat.gif tomcat.svg
bg-button.png bg-upper.png RELEASE-NOTES.txt tomcat.png WEB-INF
bg-middle.png favicon.ico tomcat.css tomcat-power.gif
可以对index.jsp进行修改相当于修改动态资源显示不同的画面
测试
Nginx盗链
盗链概念
盗链就是盗用链接,A服务使用B服务上的资源,这就是盗链
B服务不让A使用自己上面的资源就是防盗链
防盗链配置
vim /etc/nginx/nginx.conf
1.配置日志格式(添加$http_referer)
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
语法格式:
valid_referers none | blocked | server_names | string ...;
参数解析:
none: 表示不检查 Referer 字段,即不限制访问来源。
blocked: 表示只允许没有 Referer 字段或者 Referer 字段为空的请求访问。
server_names: 表示只允许来自当前服务器域名的请求访问。
string: 可以是指定的 URL 字符串,表示只允许指定的 URL 作为来源访问。
准备环境
192.168.252.147 被盗用服务
192.168.252.148 盗用服务、
配置被盗用服务
1.编辑配置文件
vim /etc/nginx/conf.d/valid.conf
server {
listen 82;
server_name localhost;
location / {
root /test/html;
index index.html index/htm;
valid_referers none blocked 192.168.252.147;
if ($invalid_referer) {
return 404;
}
}
}
2.创建目录和创建html文件
mkdir -p /test/html
vim /test/html/index.html
<html>
<head>
<meta charset="utf-8">
<title>qf.com</title>
</head>
<body style="background-color:red;">
<img src="index.jpg"/>
</body>
</html>
3.重启
nginx -t
systemctl reload nginx
systemctl restart nginx
配置盗用服务
1.编辑配置文件
server {
listen 82;
server_name localhost;
location / {
root /test/html;
index index.html;
}
}
2.创建目录和创建html文件
mkdir -p /test/html
vim /test/html/index.html
<html>
<head>
<meta charset="utf-8">
<title>qf.com</title>
</head>
<body style="background-color:red;">
<img src="http://192.168.252.147/index.jpg"/>
</body>
</html>
3.重启
nginx -t
systemctl reload nginx
systemctl restart nginx
测试
第二个日志中找不到图片,设置防盗链成功
Nginx Rewrite地址重定向
相关命令
if、rewrite、set、return、flag标记
if
应用环境
server{
...
}
location {
...
}
在这两个模块可以使
模版
模版:
server {
if ( [condition] ){
[action];
}
}
server{
location / {
if ( [condition] ){
[action];
}
}
}
规则参考
~ 为区分大小写匹配
~* 为不区分大小写匹配
= 比较变量和字符串是否相等
!= 比较变量和字符串是否不相等
!~和!~*分别为区分大小写不匹配及不区分大小写不匹配
-f和!-f用来判断是否存在文件
-d和!-d用来判断是否存在目录
-e和!-e用来判断是否存在文件或目录
-x和!-x用来判断文件是否可执行
tips:
如果$变量的值为空字符串或0,则if指令认为该条件为false,其他条件为true。
rewrite
应用场景
server、location、if
语法格式
rewrite <正则匹配规则(url路径)> <跳转后的内容(url路径)> [flag];
set
应用场景
server、location、if
语法格式
set $key value
flag
标签类型
last last标记位的location模块永远无法匹配不上,相当于这个location模块不能使用了
break 本条规则匹配完成后,终止匹配,不再匹配后面的规则
redirect 返回302临时重定向,浏览器地址会显示跳转后的URL地址
permanent 返回301永久重定向,浏览器地址会显示跳转后URL地址
应用环境
server{
...
}
location / {
...
}
if () {
...
}
模版
语法格式:
rewrite <正则匹配规则(url路径)> <跳转后的内容(url路径)> [flag];
模版:
server {
rewrite <正则匹配规则(url路径)> <跳转后的内容(url路径)> [flag];
}
server {
location {
rewrite <正则匹配规则(url路径)> <跳转后的内容(url路径)> [flag];
}
}
server {
location{
if(){
rewrite <正则匹配规则(url路径)> <跳转后的内容(url路径)> [flag];
}
}
}
注意
last和break的区别:
last和break出现在location 内部时,两者存在差异。
使用了last指令,rewrite后会跳出location作用域,重新开始再走一次刚刚的行为
使用了 break 指令,rewrite 后不会跳出location作用域。
last 和 break 当出现在 location 之外时,两者不存在差异。
跳过所有的在他们之后的rewrite模块中的指令,去选择自己匹配的location
示例:
1.编辑虚拟机配置文件
vim /etc/nginx/conf.d/last_break.conf
server {
listen 80;
server_name localhost;
location / {
root /usr/share/nginx/html;
index index.html index.htm;
}
# break: http://192.168.252.149/break ---> http://192.168.252.149/test/break.html
location /break {
root /usr/share/nginx/html;
rewrite .* /test/break.html break;
}
# last: http://192.168.252.149/last ---> http://192.168.252.149/test/last.html
# http://192.168.252.149/test/last.html ---> http://192.168.252.149/test/test.html
location /last {
root /usr/share/nginx/html;
rewrite .* /test/last.html last;
}
location /test {
root /usr/share/nginx/html;
#index test.html;
rewrite .* /test/test.html break;
}
}
2.创建目录
mkdir -p /usr/share/nginx/html/test
vim /usr/share/nginx/html/test/last.html
vim /usr/share/nginx/html/test/break.html
vim /usr/share/nginx/html/test/test.html
return
应用场景
server,location,if
语法格式
return [code| URL]
1.返回JSON
return [状态码] "{[key]:[value],...}";
2.返回状态码
return [状态码];
3.返回String字符串
return [状态码] "[字符串]";
4.返回URL
return "[url完整路径]";
Nginx平滑升级
介绍
通过在老nginx版本启动的情况下进行对nginx进行热升级(不停掉老版本的nginx进程的情况下)
思路
(1)在不停掉老进程的情况下,启动新进程。
(2)老进程负责处理仍然没有处理完的请求,但不再接受新请求。
(3)新进程接受新请求。
(4)老进程处理完所有请求,关闭所有连接后,停止。
升级情况有两种:模块升级(添加模块)和nginx版本升级
平滑升级描述
nginx 默认工作在多进程模式下,即主进程(master process)启动后完成配置加载和端口绑定等动作,fork出指定数量的工作进程(worker process),这些子进程会持有监听端口的文件描述符(fd),并通过在该描述符上添加监听事件来接受连接
Nginx信号简介
nginx: master process 主进程
信号 | 解释 |
TERM, INT | 立刻退出 |
QUIT | 等待工作进程结束后再退出 |
KILL | 强制终止进程 |
HUP | 重新加载配置文件,使用新的配置启动工作进程,并逐步关闭旧进程 |
USR1 | 重新打开日志文件 |
USR2 | 启动新的主进程,实现热升级 |
WINCH | 逐步关闭工作进程 |
nginx: worker process 工作进程
信号 | 解释 |
TERM, INT | 立刻退出 |
QUIT | 等待工作进程结束后再退出 |
USR1 | 重新打开日志文件 |
编译平滑升级
准备
192.168.252.137
nginx1.18.0 ----------> nginx 1.26.1
下载官网:nginx: download
下载安装包并解压
wget https://nginx.org/download/nginx-1.18.0.tar.gz
wget https://nginx.org/download/nginx-1.26.2.tar.gz
tar -xzvf nginx-1.18.0.tar.gz -C /usr/local/
tar -xzvf nginx-1.26.2.tar.gz -C /usr/local/
编译安装 nginx-1.18.0
cd /usr/local/nginx-1.18.0/
编译:
./configure --prefix=/usr/local/nginx --group=nginx --user=nginx --sbin-path=/usr/local/nginx/sbin/nginx --conf-path=/etc/nginx/nginx.conf --error-log-path=/var/log/nginx/error.log --http-log-path=/var/log/nginx/access.log --http-client-body-temp-path=/tmp/nginx/client_body --http-proxy-temp-path=/tmp/nginx/proxy --http-fastcgi-temp-path=/tmp/nginx/fastcgi --pid-path=/var/run/nginx.pid --lock-path=/var/lock/nginx --with-http_stub_status_module --with-http_ssl_module --with-http_gzip_static_module --with-pcre --with-http_realip_module --with-stream
安装:
make && make install
启动
/usr/local/nginx/sbin/nginx
ll /var/run/nginx.pid*
编译nginx-1.26.2
cd /usr/local/nginx-1.26.2
编译:
./configure --prefix=/usr/local/nginx --group=nginx --user=nginx --sbin-path=/usr/local/nginx/sbin/nginx --conf-path=/etc/nginx/nginx.conf --error-log-path=/var/log/nginx/error.log --http-log-path=/var/log/nginx/access.log --http-client-body-temp-path=/tmp/nginx/client_body --http-proxy-temp-path=/tmp/nginx/proxy --http-fastcgi-temp-path=/tmp/nginx/fastcgi --pid-path=/var/run/nginx.pid --lock-path=/var/lock/nginx --with-http_stub_status_module --with-http_ssl_module --with-http_gzip_static_module --with-pcre --with-http_realip_module --with-stream
只make:
make
tips:
只能make不能make install因为make install以后就会覆盖旧版本的文件就不能热升级了。
升级版本
备份原版本文件:
mv /usr/local/nginx/sbin/nginx /usr/local/nginx/sbin/nginx_bak
将新版本的二进制命令cp到新的源码包:
cp /usr/local/nginx-1.26.2/objs/nginx /usr/local/nginx/sbin/
测试新版本命令:
/usr/local/nginx/sbin/nginx -t
发送平滑迁移信号,启动新的主进程,实现热升级 :
kill -USR2 `cat /var/run/nginx.pid`
查看pid:
ll /var/run/nginx.pid*
会出现:
/var/run/nginx.pid
/var/run/nginx.pid.oldbin
关闭旧进程的pid:
kill -WINCH `cat /var/run/nginx.pid.oldbin`
重新加载配置文件,使用新的配置启动工作进程,并逐步关闭旧进程
kill -HUP `cat /var/run/nginx.pid.oldbin`
结束此次升级
kill -QUIT `cat /var/run/nginx.pid.oldbin`
访问url查看版本
curl -I http://localhost
Nginx错误页面配置
语法格式
作用域:http server location if
error_page code [ code... ] [ = | =answer-code ] uri | @named_location
tips:
示例
1.编辑配置文件
vim /etc/nginx/conf.d/errorpage.conf
server{
listen 80;
server_name localhost;
error_page 404 403 500 502 503 504 /404.html;
location = /404.html {
root /usr/local/nginx/html/errorpage;
}
}
2.创建文件
mkdir -p /usr/local/nginx/html/errorpage
vim /usr/local/nginx/html/errorpage/404.html
3.重启
nginx -t
systemctl reload nginx
systemctl restart nginx
Nginx流量限制
流量限制介绍
流量限制 (rate-limiting),是Nginx中一个非常实用,却经常被错误理解和错误配置的功能。我们可以用来限制用户在给定时间内HTTP请求的数量。请求,可以是一个简单网站首页的GET请求,也可以是登录表单的 POST 请求。流量限制可以用作安全目的,比如可以减慢暴力密码破解的速率。通过将传入请求的速率限制为真实用户的典型值,并标识目标URL地址(通过日志),还可以用来抵御 DDOS 攻击。更常见的情况,该功能被用来保护上游应用服务器不被同时太多用户请求所压垮。
”流量限制”使用漏桶算法(leaky bucket algorithm),该算法在通讯和分组交换计算机网络中广泛使用,用以处理带宽有限时的突发情况。就好比,一个桶口在倒水,桶底在漏水的水桶。如果桶口倒水的速率大于桶底的漏水速率,桶里面的水将会溢出;同样,在请求处理方面,水代表来自客户端的请求,水桶代表根据”先进先出调度算法”(FIFO)等待被处理的请求队列,桶底漏出的水代表离开缓冲区被服务器处理的请求,桶口溢出的水代表被丢弃和不被处理的请求。
流量控制相关功能
相关命令
limit_req_zone
limit_req
limit_req_status
limit_req_log_level
1.limit_req_zone
limit_req_zone [key] zone=[name]:[size] rate=[rate];
tips:
key: 必选项;取值范围: 1,text(文本); 2,nginx变量;3,text和nginx变量的组合。注: 1.7.6版本之前取值只能是nginx变量
name: 必选项;自定义字符串
size:必选项;分配内存大小,用来保存键值的状态参数
rate: 必选项;每秒可请求的频率(r/s), 或每分钟可请求的频率(r/m)
2.limit_req
limit_req zone=[name] burst=[num] nodelay;
tips:
burst 创建队列使得刷新的时候可以等待
nodelay 没有延迟刷新
3.limit_req_status
limit_req_status [code];
tips:
默认值:503
4.limit_req_log_level
limit_req_log_level [info | notice | warn | error];
tips:
默认值:error;
准备
192.168.252.148 代理端
192.168.252.149 处理端
基本限流
limit_req_zone和limit_req
示例:
192.168.252.148 代理端
1.编辑配置文件
vim /etc/nginx/conf.d/limit.conf
limit_req_zone $binary_remote_addr zone=mylimit:10m rate=1r/s;
upstream web {
server 192.168.252.149:80 weight=1 max_fails=1 fail_timeout=1;
}
server {
listen 80;
server_name localhost;
location / {
limit_req zone=mylimit;
proxy_pass http://web;
proxy_set_header Host $host:$server_port;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
2.重启
nginx -t
systemctl reload nginx
systemctl restart nginx
192.168.252.149 处理端
1.编辑配置文件
vim /etc/nginx/conf.d/limit.conf
server {
listen 80;
server_name localhost;
location / {
root /limit/html;
index index.html;
}
}
2.创建目录和文件
mkdir -p /limit/html
vim /limit/html/index.html
3.重启
nginx -t
systemctl reload nginx
systemctl restart nginx
4.访问页面快速刷新两次就会显示503访问失败
突发处理
指定burst 数量可以延迟网页访问将下一次访问的页面进行排队相当于缓冲任何超额的请求。
burst
示例:
192.168.252.148 代理端
1.编辑配置文件
vim /etc/nginx/conf.d/limit_burst.conf
limit_req_zone $binary_remote_addr zone=mylimit:10m rate=1r/s;
upstream web {
server 192.168.252.149:80 weight=1 max_fails=1 fail_timeout=1;
}
server {
listen 80;
server_name localhost;
location / {
limit_req zone=mylimit burst=3; #进行排队数量为3
proxy_pass http://web;
proxy_set_header Host $host:$server_port;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
2.重启
nginx -t
systemctl reload nginx
systemctl restart nginx
192.168.252.149 处理端
1.编辑配置文件
vim /etc/nginx/conf.d/limit.conf
server {
listen 80;
server_name localhost;
location / {
root /limit/html;
index index.html;
}
}
2.创建目录和文件
mkdir -p /limit/html
vim /limit/html/index.html
3.重启
nginx -t
systemctl reload nginx
systemctl restart nginx
4.访问页面快速刷新两次标题部分会出现转圈加载不会出现
无延迟排队
当使用burst 的时候连续访问页面会造成页面延迟使用nodelay后可以无延迟进行访问
nodelay 和 burst
示例:
192.168.252.148 代理端
1.编辑配置文件
vim /etc/nginx/conf.d/limit_nodelay.conf
limit_req_zone $binary_remote_addr zone=mylimit:5M rate=1r/s;
server {
listen 80;
server_name localhost;
location / {
limit_req zone=mylimit burst=3 nodelay;
proxy_pass http://192.168.252.149:80;
proxy_set_header Host $host:$server_port;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
2.重启
nginx -t
systemctl reload nginx
systemctl restart nginx
192.168.252.149 处理端
1.编辑配置文件
vim /etc/nginx/conf.d/limit.conf
server {
listen 80;
server_name localhost;
location / {
root /limit/html;
index index.html;
}
}
2.创建目录和文件
mkdir -p /limit/html
vim /limit/html/index.html
3.重启
nginx -t
systemctl reload nginx
systemctl restart nginx
4.访问页面快速刷新两次标题部分会出现503
限制并发连接
limit_conn和limit_conn_zone
myvip限制单个IP同时并发连接数最多只能10个连接
myServerName限制整个虚拟服务器同时最大并发数最多只能100个连接
请求的header被服务器处理后,虚拟服务器的连接数才会计数
192.168.252.148 代理端
1.编辑配置文件
vim /etc/nginx/conf.d/limit_conn.conf
limit_conn_zone $binary_remote_addr zone=myip:10m;
limit_conn_zone $server_name zone=myServerName:10m;
server {
listen 80;
server_name localhost;
location / {
limit_conn myip 10;
limit_conn myServerName 100;
proxy_pass http://192.168.252.149:80;
}
}
2.重启
nginx -t
systemctl reload nginx
systemctl restart nginx
192.168.252.149 处理端
1.编辑配置文件
vim /etc/nginx/conf.d/limit.conf
server {
listen 80;
server_name localhost;
location / {
root /limit/html;
index index.html;
}
}
2.创建目录和文件
mkdir -p /limit/html
vim /limit/html/index.html
3.重启
nginx -t
systemctl reload nginx
systemctl restart nginx
4.访问页面如果同一个ip网段超过10个或者所有网段超过100个就会返回不正确的页面
配置日志记录
limit_req_log_level
日志记录字段:
limiting requests - 表明日志条目记录的是被“流量限制”请求
excess - 每毫秒超过对应“流量限制”配置的请求数量
zone - 定义实施“流量限制”的区域
client - 发起请求的客户端IP地址
server - 服务器IP地址或主机名
request - 客户端发起的实际HTTP请求
host - HTTP报头中host的值
默认情况下,Nginx以error级别来记录被拒绝的请求
192.168.252.148 代理端
1.编辑主配置文件
error_log /var/log/nginx/error.log warn;
2.编辑虚拟主机配置文件
vim /etc/nginx/conf.d/limit_level.conf
limit_req_zone $binary_remote_addr zone=mylimit:5M rate=1r/s;
server {
listen 80;
server_name localhost;
location / {
limit_req zone=mylimit;
limit_req_log_level warn;
proxy_pass http://192.168.252.149:80;
}
}
3.重启配置文件
nginx -t
systemctl reload nginx
systemctl restart nginx
192.168.252.149 处理端
1.编辑配置文件
vim /etc/nginx/conf.d/limit.conf
server {
listen 80;
server_name localhost;
location / {
root /limit/html;
index index.html;
}
}
2.创建目录和文件
mkdir -p /limit/html
vim /limit/html/index.html
3.重启
nginx -t
systemctl reload nginx
systemctl restart nginx
4.查看日志
tail -f /var/log/nginx/error.log
2024/08/30 20:54:22 [warn] 3125#3125: *1 limiting requests, excess: 0.845 by zone "mylimit", client: 192.168.252.1, server: localhost, request: "GET / HTTP/1.1", host: "192.168.252.148"
客户端错误代码控制
访问限制后出现的http响应状态码
limit_req_status
192.168.252.148 代理端
1.编辑虚拟主机配置文件
vim /etc/nginx/conf.d/limit_status.conf
limit_req_zone $binary_remote_addr zone=mylimit:5M rate=1r/s;
server {
listen 80;
server_name localhost;
location / {
proxy_pass http://192.148.252.149:80;
limit_req zone=mylimit;
limit_req_status 504;
}
}
2.重启配置文件
nginx -t
systemctl reload nginx
systemctl restart nginx
192.168.252.149 服务端
1.编辑配置文件
vim /etc/nginx/conf.d/limit.conf
server {
listen 80;
server_name localhost;
location / {
root /limit/html;
index index.html;
}
}
2.创建目录和文件
mkdir -p /limit/html
vim /limit/html/index.html
3.重启
nginx -t
systemctl reload nginx
systemctl restart nginx
4.访问连续点击两次访问到504界面
Nginx访问控制
相关命令:
allow [IpAddress | CIDR | unix: | all];
deny [IpAddress | CIDR | unix: | all];
tips:
如果先定义allow允许访问的ip,再定义deny拒绝访问的ip。那么拒绝访问的ip不生效。
拒绝访问的ip如果访问将显示403
准备
192.168.252.148 服务端
192.168.252.149 访问端
基于ip访问控制
语法:
allow [允许访问的ip]
deny [不允许访问的ip]
allow all #允许所有ip访问
deny all #任何ip不许访问
tips:
网段配置
allow 192.168.1.0/24;
示例:
192.168.252.148 服务端
1.编辑配置文件
vim /etc/nginx/conf.d/control_access.conf
配置文件:
server {
listen 80;
server_name localhost;
location / {
root /usr/share/nginx/html;
#deny all; #拒绝所有请求
deny 192.168.252.149;
allow all;
#deny 192.168.252.149;
index index.html index.htm;
}
}
2.重启配置文件
nginx -t
systemctl reload nginx
systemctl restart nginx
192.168.252.149 访问端
1.curl访问服务端
curl -I http://192.168.252.148
HTTP/1.1 403 Forbidden
Server: nginx/1.26.1
Date: Sat, 31 Aug 2024 02:51:11 GMT
Content-Type: text/html
Content-Length: 153
Connection: keep-alive
2.window访问
可以访问200 OK
基于用户信任登录
相关命令:
auth_basic [string | off];
auth_basic_user_file [file];
tips:
auth_basic 不为off,开启登录验证功能
auth_basic_user_file 加载账号密码文件。
示例:
1.建立口令文件
yum -y install httpd-tools
2.创建用户
htpasswd -cm /etc/nginx/auth_conf user01 #第一次创建用户要加-c
htpasswd -m /etc/nginx/auth_conf user02 #第二次创建用户
cat /etc/nginx/auth_conf #查看密码文件
user01:$apr1$AkVwcdWk$qbKuI2BSOIyQ7/i4TZfSy/
user02:$apr1$Tq6gH9pT$V7ulQOrpqt9pW7o/mypnM/
3.编辑配置文件
vim /etc/nginx/conf.d/user_access.conf
配置文件中:
server {
listen 80;
server_name localhost;
location / {
root /usr/share/nginx/html;
index index.html index.htm;
auth_basic "Auth access test!";
auth_basic_user_file /etc/nginx/auth_conf;
}
}
4.创建发布目录文件
mkdir -p /usr/share/nginx/html
vim /usr/share/nginx/html/index.html
5.重启配置文件
nginx -t
systemctl reload nginx
systemctl restart nginx
六、Nginx日志
日志介绍
Nginx的日志分为两类:访问日志(access log)和错误日志(error log)。访问日志记录了每个请求的详细信息,而错误日志记录了服务器处理请求时遇到的问题。
access.log用于存放每个用户访问网站的请求日志,开发运维人员通过访问日志来分析用户的浏览器行为。
error.log记录了nginx运行过程中遇到的错误信息(注意,也包括用户请求没有正常响应的错误日志),向有时候我们nginx启动失败后,都可以在这个error日志中找到对应较为详情的报错信息。
rewrite的日志是重写在error.log中
yum安装日志位置:
/var/log/nginx/access.log 访问日志
/var/log/nginx/error.log 错误日志
日志的配置
日志的作用域
server http locaiton if
日志格式
语法:
log_format [name] [escape=default|json] [string] ...;
tips:
name 格式名称。在 access_log 指令中引用。
escape 设置变量中的字符编码方式是json还是default,默认是default。
string 要定义的日志格式内容。该参数可以有多个。参数中可以使用Nginx变量。
预定义日志格式:
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
cat /var/log/nginx/access.log
192.168.252.1 - - [29/Aug/2024:19:28:15 +0800] "GET /log/ HTTP/1.1" 200 4 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36"
日志的常用变量:
$time_local 通用日志格式下的本地时间;(服务器时间)
$remote_addr 客户端(用户)IP地址
$status 请求状态码,如200,404,301,302等
$body_bytes_sent 发送给客户端的字节数,不包括响应头的大小
$bytes_sent 发送给客户端的总字节数
$request_length 请求的长度(包括请求行,请求头和请求正文)
$request_time 请求处理时间,单位为秒,小数的形式
$upstream_addr 集群轮询地址
$upstream_response_time 指从Nginx向后端(php-cgi)建立连接开始到接受完数据然后关闭连接为止的时间
$remote_user 用来记录客户端用户名称
$request 请求方式(GET或者POST等)+URL(包含$request_method,$host,$request_uri)
$http_user_agent 用户浏览器标识
$http_host 请求的url地址(目标url地址)的host
$host 等同于$http_host
$http_referer 来源页面,即从哪个页面转到本页,如果直接在浏览器输入网址来访问,则referer为空
$uri 请求中的当前URI(不带请求参数,参数位于$args),不同于浏览器传递的$request_uri的值,它可以通过内部重定向,或者使用index指令进行修改。
$document_uri 等同于$uri
$request_uri 比$uri多了参数,即$uri+$args
$http_x_forwarded_for 如果使用了代理,这个参数会记录代理服务器的ip和客户端的ip
访问日志
将虚拟主机的访问信息记录在访问日志中
语法格式:
语法:
access_log [path] [name];
tips:
1.[name]对应log_format中的[name]
2.在http中设置可以控制所有server(没设置access_log的前提)的access日志
3.在server中设置可以设置当前虚拟机的access日志
4.如果所有server都设置access_log http中的access_log就会失效
5.如果一个server中设置一个server不设置,http中设置http将输出那个没有设置的server的access.log
示例:
1.编辑虚拟主机配置文件
vim /etc/nginx/conf.d/access_log.conf
server {
listen 80;
server_name localhost;
access_log /access/log/access_80.log main;
location /access80 {
root /access/html;
index index.html index.htm;
}
}
server {
listen 81;
server_name localhost;
access_log /access/log/access_81.log main;
location /access81 {
root /access/html;
index index.html index.htm;
}
}
2.编辑主配置文件
vim /etc/nginx/conf.d/nginx.html
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log notice;
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;
#tcp_nopush on;
keepalive_timeout 65;
#gzip on;
include /etc/nginx/conf.d/*.conf;
}
2.创建目录文件
mkdir -p /access/log/
mkdir -p /access/html/access80
mkdir -p /access/html/access81
echo "access80" >> /access/html/access80/index.html
echo "access81" >> /access/html/access81/index.html
3.重启
nginx -t
systemctl reload nginx
systemctl restart nginx
80日志:(输出)
81日志:(输出)
/var/log/nginx/access.log
错误日志
记录服务器和请求处理过程中的错误信息
由ngx_http_rewrite_module模块提供的。用来记录重写日志的。对于调试重写规则建议开启,启用时将在error log中记录重写日志。
语法:
error_log [path] [level];
tips:
[level] 错误等级,错误级别等于或高于[level]指定的值才会写入错误日志中
debug, info, notice, warn, error, crit, alert,emerg
错误等级:低-------->高
示例:
1.编辑配置文件
vim /etc/nginx/conf.d/error_log.conf
server {
listen 80;
server_name localhost;
error_log /error/log/error.log notice;
location / {
root /error/html;
index index.html;
}
}
2.创建目录文件
mkdir -p /error/log
mkdir -p /error/html;
vim /error/html/index.html
3.重启
nginx -t
systemctl reload nginx
systemctl restart nginx
重定向日志
rewrite_log属于notice级别。只会记录在error_log中,那么记得将error_log的级别设置为notice;
语法:
语法:
rewrite_log [on | off];
tips:
默认值:
rewrite_log off;
作用域:http server if location
示例:
1.编辑配置文件(error_log必须是notice级别)
vim /etc/nginx/conf.d/rewrite_log.conf
server {
listen 80;
server_name www.testmp.com;
access_log /var/log/nginx/access_rewrite.log main;
error_log /var/log/nginx/error_rewrite.log notice;
rewrite_log on;
location / {
if ( $host ~* ^www.testmp.com$ ){
rewrite .* http://www.baidu.com permanent;
}
}
}
日志轮转
1.查看Nginx的日志轮轮转文件路径
rpm -ql nginx |grep log
/etc/logrotate.d/nginx
/var/log/nginx
2.日志轮转
vim /etc/logrotate.d/nginx
/var/log/nginx/*.log { #指定需要轮转处理的日志文件
daily #日志文件轮转周期,可用值为: daily/weekly/yearly
missingok # 忽略错误信息
rotate 7 # 轮转次数,即最多存储7个归档日志,会删除最久的归档日志
minsize 5M #限制条件,大于5M的日志文件才进行分割,否则不操作
dateext # 以当前日期作为命名格式
compress # 轮循结束后,已归档日志使用gzip进行压缩
delaycompress # 与compress共用,最近的一次归档不要压缩
notifempty # 日志文件为空,轮转不会继续执行
create 640 nginx nginx #新日志文件的权限
sharedscripts #有多个日志需要轮询时,只执行一次脚本
postrotate # 将日志文件转储后执行的命令。以endscript结尾,命令需要单独成行
if [ -f /var/run/nginx.pid ]; then #判断nginx的PID。# 默认logrotate会以root身份运行
kill -USR1 `cat /var/run/nginx.pid`
fi
endscript
}
3.执行命令
logrotate -f /etc/logrotate.conf
4.计划任务
crontab -e
59 23 * * * /usr/sbin/logrotate -f /etc/logrotate.conf
七、Nginx的HTTPS和HTTP的部署
阿里云
申购服务器
腾讯云免费申请服务器(仅限新用户哟!!!)
轻量应用服务器Lighthouse_香港轻量服务器_海外轻量服务器-腾讯云
申购域名
给域名创建模版
填写模版的实名信息
域名购买成功
进行信息模版实名验证
SSL证书申购
进入个人测试SSL证书
购买ssl免费个人测试版
域名SSL证书申请
审核测试验证DNS是否配置成功
完成
Nginx证书服务配置
下载证书
配置解析
配置解析到的一级域名和选择A默认匹配到本机虚拟机的ip
本地配置SSL证书
mkdir -p /etc/nginx/cert
cd /etc/nginx/cert
上传证书 14804979_www.syhwyq.icu_nginx.zip
1.解压查看
unzip 14804979_www.syhwyq.icu_nginx.zip
ll
-rw-r--r-- 1 root root 4101 9月 2 13:48 14804979_www.syhwyq.icu_nginx.zip
-rw-r--r-- 1 root root 1675 9月 2 13:47 www.syhwyq.icu.key
-rw-r--r-- 1 root root 3822 9月 2 13:47 www.syhwyq.icu.pem
2.编辑配置文件
vim /etc/nginx/conf.d/nginx_ssl.conf
server {
listen 80;
server_name www.syhwyq.icu;
location / {
root /usr/share/nginx/html;
index index.html index.htm;
}
}
server {
listen 443 ssl;
server_name www.syhwyq.icu;
ssl_certificate /etc/nginx/cert/www.syhwyq.icu.pem;
ssl_certificate_key /etc/nginx/cert/www.syhwyq.icu.key;
ssl_session_cache shared:SSL:1m;
ssl_session_timeout 5m;
ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4;
ssl_protocols TLSv1.1 TLSv1.2 TLSv1.3;
ssl_prefer_server_ciphers on;
location / {
root /usr/share/nginx/html;
index index.html index.htm;
}
}
3.重启
systemctl reload nginx
4.访问
https://www.syhwyq.icu
八、Nginx监控
Nginx监控指标
Nginx的nginx Stub Status 监控模块
参数
1.查看是否安装with-http_stub_status_module模块
nginx -V
2.编译安装的时候指定 --with-http_stub_status_module(可选,使用nginx -V 看是否有此模块下面适用于yum安装的nginx)
./configure --prefix=/etc/nginx --sbin-path=/usr/sbin/nginx --modules-path=/usr/lib64/nginx/modules --conf-path=/etc/nginx/nginx.conf --error-log-path=/var/log/nginx/error.log --http-log-path=/var/log/nginx/access.log --pid-path=/var/run/nginx.pid --lock-path=/var/run/nginx.lock --http-client-body-temp-path=/var/cache/nginx/client_temp --http-proxy-temp-path=/var/cache/nginx/proxy_temp --http-fastcgi-temp-path=/var/cache/nginx/fastcgi_temp --http-uwsgi-temp-path=/var/cache/nginx/uwsgi_temp --http-scgi-temp-path=/var/cache/nginx/scgi_temp --user=nginx --group=nginx --with-compat --with-file-aio --with-threads --with-http_addition_module --with-http_auth_request_module --with-http_dav_module --with-http_flv_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_mp4_module --with-http_random_index_module --with-http_realip_module --with-http_secure_link_module --with-http_slice_module --with-http_ssl_module --with-http_stub_status_module --with-http_sub_module --with-http_v2_module --with-mail --with-mail_ssl_module --with-stream --with-stream_realip_module --with-stream_ssl_module --with-stream_ssl_preread_module --with-cc-opt='-O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector-strong --param=ssp-buffer-size=4 -grecord-gcc-switches -m64 -mtune=generic -fPIC' --with-ld-opt='-Wl,-z,relro -Wl,-z,now -pie' --add-module=/usr/local/echo-nginx-module
3.编辑配置文件
vim /etc/nginx/conf.d/stub_status.conf
server {
listen 80;
server_name localhost;
location /nginx-status {
stub_status on;
access_log off;
}
}
4.重启
systemctl restart nginx
5.访问查看Nginx状态
linux:
curl http://192.168.252.149/nginx-status
windows:
http://192.168.252.149/nginx-status
Nginx的Reqstat 模块监控
1.下载模块
wget https://github.com/zls0424/ngx_req_status/archive/master.zip -O ngx_req_status.zip
unzip ngx_req_status.zip
cp -r ngx_req_status-master/ /usr/local/
2.编译安装此模块
yum -y install pcre pcre-devel openssl openssl-devel gcc gcc-c++ zlib zlib-devel
yum -y install patch.x86_64
cd /usr/local/nginx-1.26.2/
patch -p1 < ../ngx_req_status-master/write_filter-1.7.11.patch
.configure [加上nginx -V 的预编译参数] --add-module=/usr/local/ngx_req_status-master
make
3.覆盖命令
mv /usr/sbin/nginx /usr/sbin/nginx_bak
cp objs/nginx /usr/sbin/
nginx -V
4.配置虚拟主机访问监控
vim /etc/nginx/conf.d/reqstat.conf
req_status_zone server_name $server_name 256k;
req_status_zone server_addr $server_addr 256k;
req_status_zone server_url $server_name$uri 256k;
req_status server_name server_addr server_url;
server {
listen 80;
server_name localhost;
location /req-status {
req_status_show on;
}
}
5.重启
systemctl reload nginx
6.本地访问
curl localhost/req-status
zone_name key max_active max_bw traffic requests active bandwidth
server_addr 127.0.0.1 1 0 1024 2 1 0
server_name localhost 1 0 1024 2 1 0
server_url localhost/req-status 1 0 1024 2 1 0
参数解释:
zone_name 利用req_status_zone定义的分组标准。例如,按照服务器名称对请求进行分组后
key 请求按分组标准分组后的分组标识(即组名)。例如按服务器名称分组时,组名可能是localhost
max_active 该组的最大并发连接数
max_bw 该组的最大带宽
traffic 该组的总流量
requests 该组的总请求数
active 该组当前的并发连接数
bandwidth 该组当前带宽
九、Nginx性能优化
优化方面
了解系统结构瓶颈
1.了解当前系统的瓶颈,了解服务是一个什么结构,服务支持多大并发
2.查看当前cpu负荷,内存使用率,进程使用率,通过操作系统的一些工具来判断当前系统性能瓶颈,分析对应的日志,查看请求数量。通过nginx_http_stub_status_module模块来查看对应的连接数,总握手次数,总请求数.
对线上进行压力测试,来了解当前的系统的性能,并发数,做好性能评估。
了解业务模式
了解每一个接口业务类型是什么样的业务,在某个接口业务在各个时间段的流量,了解系统层级结构,在系统的每一层是做代理还是动静分离。需要我们对业务接入层和系统层次要有一个梳理。
了解性能与安全
需要把把握好性能和安全之间的平衡。不能安全好但性能不好导致用户体验差,不能性能好安全差,这样子会造成数据被盗取,对公司业务影响不好。应该平衡性能和安全
系统与Nginx性能优化
影响性能的因素
- 网络(网络流量、是否有丢包,网络的稳定性都会影响用户请求)
- 系统(系统负载、饱和、内存使用率、系统的稳定性、硬件磁盘是否有损坏)
- 服务(连接优化、内核性能优化、http服务请求优化都可以在nginx中根据业务来进行设置)
- 程序(接口性能、处理请求速度、每个程序的执行效率)
- 数据库、底层服务
Nginx层
文件句柄
文件句柄就是一个索引。文件句柄就会随着请求量的增多,进程调用频繁增加,那么产生的文件句柄也就会越多。系统默认对文件句柄是有限制的,不可能会让一个进程无限制的调用句柄。因为系统资源是有限的,所以我们需要限制每一个服务能够使用多大的文件句柄。操作系统默认使用的文件句柄是1024个句柄。
文件句柄的设置方式
- 系统全局性修改
- 用户局部性修改
- 进程局部性修改
系统全局性修改
vim /etc/security/limits.conf
在最后添加:
#root只是针对root这个用户来限制,soft只是发提醒,操作系统不会强制限制,一般的站点设置为一万左右就ok了
root soft nofile 65535
root hard nofile 65535
# End of file
用户局部性修改
vim /etc/security/limits.conf
# *代表通配符 所有的用户
* soft nofile 25535
* hard nofile 25535
# End of file
进程局部性修改
vim /etc/nginx/nginx.conf
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log notice;
pid /var/run/nginx.pid;
worker_rlimit_nofile 25535; #进程限制
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;
rewrite_log on;
sendfile on;
#tcp_nopush on;
keepalive_timeout 65;
#gzip on;
include /etc/nginx/conf.d/*.conf;
}
gzip 压缩优化
Nginx开启Gzip压缩功能, 可以使网站的静态文件文件在传输时进行压缩,提高访问速度, 进而优化Nginx性能
文件压缩:
图片,视频等其它多媒体文件以及大文件的优化方式:图片的生命周期或视频设置长一点,让客户端来缓存。(原因:压缩效果不好)
css、js、xml、html等文件的优化方式:Gzip压缩(压缩效果好,使得这些内容大小减少,以压缩后的数据展现给客户)
特点:
- 节约大量的出口带宽,提高传输效率
- 消耗部分cpu资源,提高传输效率
- 提升用户的感知体验
Nginx参数
gzip on; #决定是否开启gzip模块,on表示开启,off表示关闭;
gzip_min_length 1k; #设置允许压缩的页面最小字节(从header头的Content-Length中获取) ,当返回内容大于此值时才会使用gzip进行压缩,以K为单位,当值为0时,所有页面都进行压缩。建议大于1k
gzip_buffers 4 16k; #设置gzip申请内存的大小,其作用是按块大小的倍数申请内存空间,param2:int(k) 后面单位是k。这里设置以16k为单位,按照原始数据大小以16k为单位的4倍申请内存
gzip_http_version 1.1; #识别http协议的版本,早起浏览器可能不支持gzip自解压,用户会看到乱码
gzip_comp_level 2; #设置gzip压缩等级,等级越低压缩速度越快文件压缩比越小,反之速度越慢文件压缩比越大;等级1-9,最小的压缩最快 但是消耗cpu
gzip_types text/plain application/x-javascript text/css application/xml; #设置需要压缩的MIME类型,非设置值不进行压缩,即匹配压缩类型
gzip_vary on; #启用应答头"Vary: Accept-Encoding"
gzip_proxied off;
nginx做为反向代理时启用,off(关闭所有代理结果的数据的压缩),expired(启用压缩,如果header头中包括"Expires"头信息),no-cache(启用压缩,header头中包含"Cache-Control:no-cache"),
no-store(启用压缩,header头中包含"Cache-Control:no-store"),private(启用压缩,header头中包含"Cache-Control:private"),no_last_modefied(启用压缩,header头中不包含
"Last-Modified"),no_etag(启用压缩,如果header头中不包含"Etag"头信息),auth(启用压缩,如果header头中包含"Authorization"头信息)
gzip_disable msie6;
(IE5.5和IE6 SP1使用msie6参数来禁止gzip压缩 )指定哪些不需要gzip压缩的浏览器(将和User-Agents进行匹配),依赖于PCRE库
示例
不开启gzip
主配置文件:
vim /etc/nginx/nginx.conf
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;
#tcp_nopush on;
keepalive_timeout 65;
#gzip on;
include /etc/nginx/conf.d/*.conf;
}
子配置文件:
vim /etc/nginx/conf.d/gziptest.conf
server {
listen 80;
server_name localhost;
location / {
root /usr/share/nginx/html/Jump;
index index.html index.htm;
}
}
重启访问
开启gzip
主配置文件:
vim /etc/nginx/nginx.conf
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;
#tcp_nopush on;
keepalive_timeout 65;
gzip on;
gzip_min_length 1k;
gzip_buffers 4 16k;
gzip_http_version 1.1;
gzip_comp_level 9;
gzip_types image/jpg text/css text/xml text/htm application/javascript;
include /etc/nginx/conf.d/*.conf;
}
子配置文件:
vim /etc/nginx/conf.d/gziptest.conf
server {
listen 80;
server_name localhost;
location / {
root /usr/share/nginx/html/Jump;
index index.html index.htm;
}
}
重启访问
由于上图的原本大小小于1k所以不进行压缩
CPU的亲和配置
cpu的亲和能够使nginx对于不同的work工作进程绑定到不同的cpu上面去。就能够减少在work间不断切换cpu,把进程通常不会在处理器之间频繁迁移,进程迁移的频率小,来减少性能损耗。
cat /proc/cpuinfo|grep "cpu cores"|uniq # 查看CPU的核心数
top #动态查看CPU的使用率
Nginx配置与CPU亲和
worker_processes
指令
worker_processes [size|auto];
nginx的工作进程数
vim /etc/nginx/nginx.conf
user nginx;
worker_processes auto; # 后面跟的个数是跟CPU的核心数相同是最好的,也可以使用auto自动与CPU核心数匹配。
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;
#tcp_nopush on;
keepalive_timeout 65;
#gzip on;
include /etc/nginx/conf.d/*.conf;
}
worker_cpu_affinity
nginx的cpu核心切换运行机制,实现控制进程平均分配到多颗CPU
指令
worker_cpu_affinity [ cpu如何分配 | auto]
vim /etc/nginx/nginx.conf
user nginx;
worker_processes auto;
worker_cpu_affinity auto; #配置进程平均分配到CPU
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;
#tcp_nopush on;
keepalive_timeout 65;
#gzip on;
include /etc/nginx/conf.d/*.conf;
}
Nginx开启上传功能
可以限制上传的大小,例如上传证件找的时候可能需要小于多少kb的才能上传
指令
client_max_body_size [size];
默认:client_max_body_size 1m;
作用域:http location server
示例
vim /etc/nginx/nginx.conf
user nginx;
worker_processes auto;
worker_cpu_affinity auto; #配置进程平均分配到CPU
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;
#tcp_nopush on;
keepalive_timeout 65;
client_max_body_size 10m; #限制上传大小为10m
#gzip on;
include /etc/nginx/conf.d/*.conf;
}
Nginx缓存功能
反向代理缓存配置
指令
代理端参数:
proxy_cache_path [Path] levels=1:2 inactive=[time] keys_zone=[name]:[size] max_size=[size];
参数解释:
[Path] # 缓存文件存放的路径
levels # 数字表示用1位或者2位来命名目录,
inactive(可选) # 未被访问文件在缓存中保留时间
key_zone # 在共享内存中设置一块存储区域来存放缓存的key字符串,1m可以存储8000个key;
max_size(可选) # 最大cache空间如果不指定,会使用掉所有磁盘空间。当达到配额后,会删除最少使用的cache文件。
服务端参数:
示例
192.168.252.148 proxy
192.168.252.149 server
配置cache之前
192.168.252.148 proxy
1.配置代理转发
vim /etc/nginx/conf.d/cache_proxy.conf
server {
listen 80;
server_name localhost;
location / {
proxy_pass http://192.168.252.149;
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
2.重启
nginx -t
systemctl reload nginx
systemctl restart nginx
192.168.252.149 server
1.配置文件
vim /etc/nginx/conf.d/cache_server.conf
server {
listen 80;
server_name localhost;
location / {
root /usr/share/nginx/html;
index index.html;
}
}
2.创建发布目录
mkdir -p /usr/share/nginx/html
vim index.html
3.重启
nginx -t
systemctl reload nginx
systemctl restart nginx
192.168.252.148 proxy
访问:
curl -I http://192.168.252.148/
访问页面成功,无cache记录
配置cache之后
192.168.62.148 proxy
1.配置代理转发
vim /etc/nginx/conf.d/cache_proxy.conf
proxy_cache_path /tmp/nginx/cache levels=1:2 inactive=60s keys_zone=mycache:10m max_size=10g;
server {
listen 80;
server_name localhost;
location / {
proxy_pass http://192.168.252.149;
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_cache mycache;
add_header cache $upstream_cache_status;
}
}
2.创建缓存目录重启
mkdir -p /tmp/nginx/cache
nginx -t
systemctl reload nginx
systemctl restart nginx
192.168.252.149 server
1.修改配置文件
vim /etc/nginx/conf.d/cache_server.conf
server {
listen 80;
server_name localhost;
location / {
root /usr/share/nginx/html;
index index.html;
add_header X-Accel-Expires 100;
}
}
2.重启
nginx -t
systemctl reload nginx
systemctl restart nginx
192.168.62.148 proxy
1.访问
curl -I https://192.168.252.148/
缓存文件
192.168.252.148 proxy
Nginx隐藏版本号
指令
server_tokens [on|off];
默认:开启
tips:
将server_tokens off;添加到http模块下即可实现版本号隐藏