NGINX
1、IO模型
1、同步|异步
同步:点餐后老板不会通知你做好了,你得自己不停去问好了没
异步:点餐后饭好了老板主动叫你
2、阻塞|非阻塞
阻塞:点餐后等着饭,啥也干不了
非阻塞:点餐后想干嘛干嘛
2、网络IO
2.1 同步阻塞型
用户调用系统内核来进行IO操作
当发出指令后,需要等待内核接收到网络报文,并将其成功转发到用户空间才完成此次调用,在此期间啥也干不了,cpu分片时间未被充分利用,造成大量浪费
优缺点:
优: 程序简单,等待期间cpu使用率低,cpu负载低
缺: 每个请求均由独立的线程或进程完成,当并发量大时 cpu由于数量不足会频繁进行切换,且线程多了也占用内存,内存占用也高
2.2 同步非阻塞型
用户调用系统内核进行io 操作
当发出指令后立即返回结果,需要不简单请求,在内核接收报文之前一直发起,直到内核收到报文将其转发给用户
此类型对cpu造成无意义的资源浪费,一般不直接使用此模型
2.3 多路io复用型
系统监视一组socket,当内核收到所监视的socket请求的io报文到达后,会通知用户进程,用户再执行io操作
2.4 信号驱动io模型
异步非阻塞
当调用内核io时不用阻塞,且内核会在数据达到后发信号通知用户
2.5 异步 I/O 模型
和信号驱动类似,但不是通知信号用户可以进行io 而是进行完io 后通知用户已完成
3、零拷贝
系统的内存及io操作是用户代码会单独分出一部分空间,要进行io需要从内核空间拿去,内核空间从文件或网络拿取,基于指针的映射关系,可以直接让传输发生在内存上而不需要经过用户内存空间,大大提升io效率,编程中的copy和指针引用
4、nginx介绍
4.1 功能
静态的web资源服务器html,图片,js,css,txt等静态资源
http/https协议的反向代理
结合FastCGI/uWSGI/SCGI等协议反向代理动态资源请求
tcp/udp协议的请求转发(反向代理)
imap4/pop3协议的反向代理
4.2 应用特点
模块化设计,较好的扩展性
高可靠性
支持热部署:不停机更新配置文件,升级版本,更换日志文件
低内存消耗:10000个keep-alive连接模式下的非活动连接,仅需2.5M内存
event-driven,aio,mmap(零拷页),sendfile
4.3 web服务特点
虚拟主机(server)
支持 keep-alive 和管道连接(利用一个连接做多次请求)
访问日志(支持基于日志缓冲提高其性能)
url rewirte
路径别名
基于IP及用户的访问控制
支持速率限制及并发数限制
重新配置和在线升级而无须中断客户的工作进程
5、架构
5.1 程序
5.2 进程架构
5.2.1 master
对外接口:接收外部的操作(信号)
对内转发:根据外部的操作的不同,通过信号管理 Worker
监控:监控 worker 进程的运行状态,worker 进程异常终止后,自动重启 worker 进程
读取Nginx 配置文件并验证其有效性和正确性
建立、绑定和关闭socket连接
按照配置生成、管理和结束工作进程
接受外界指令,比如重启、升级及退出服务器等指令
不中断服务,实现平滑升级,重启服务并应用新的配置
开启日志文件,获取文件描述符
不中断服务,实现平滑升级,升级失败进行回滚处理
编译和处理perl脚本
5.2.2 worker
所有 Worker 进程都是平等的
实际处理:网络请求由 Worker 进程处理
Worker进程数量:一般设置为核心数,充分利用CPU资源,同时避免进程数量过多,导致进程竞争CPU资源,
增加上下文切换的损耗
接受处理客户的请求
将请求依次送入各个功能模块进行处理
I/O调用,获取响应数据
与后端服务器通信,接收后端服务器的处理结果
缓存数据,访问缓存索引,查询和调用缓存数据
发送请求结果,响应客户的请求
接收主程序指令,比如重启、升级和退出等
5.2.3 进程通信模型
5.2.3.1 主与worker
主进程根据配置生成worker进程,并且建立一张表来进行动态统计,并与每个worker建立单向的发送通道发送worker需要的信息
5.2.3.2 worker与worker
worker之间通信依赖于master,当需要通信时master会将其余worker的信息通过管道进行发送使其能建立通道进行连接,由于它们处于同一进程所以内存空间共享
5.2.3.3 主与外
通过信号接收请求,kill -s
6、安装和升级
6.1 编译安装
SRC_DIR=/usr/local/src
NGINX_URL=http://nginx.org/download/
NGINX_FILE=nginx-1.20.0
TAR=.tar.gz
NGINX_INSTALL_DIR=/apps/nginx
CPUS=`lscpu |awk '/^CPU\(s\)/{print $2}' `
color () {
RES_COL=60
MOVE_TO_COL="echo -en \\033[${RES_COL} G"
SETCOLOR_SUCCESS="echo -en \\033[1;32m"
SETCOLOR_FAILURE="echo -en \\033[1;31m"
SETCOLOR_WARNING="echo -en \\033[1;33m"
SETCOLOR_NORMAL="echo -en \E[0m"
echo -n "$1 " && $MOVE_TO_COL
echo -n "["
if [ $2 = "success" -o $2 = "0" ] ;then
${SET1COLOR_SUCCESS}
echo -n $"OK"
elif [ $2 = "failure" -o $2 = "1" ] ;then
${SETCOLOR_FAILURE}
echo -n $"FAILED"
else
${SETCOLOR_WARNING}
echo -n $"WARNING"
fi
${SETCOLOR_NORMAL}
echo -n "]"
echo
}
os_type () {
awk -F'[ "]' '/^NAME/{print $2}' /etc/os-release
}
os_version () {
awk -F'"' '/^VERSION_ID/{print $2}' /etc/os-release
}
check () {
[ -e ${NGINX_INSTALL_DIR} ] && { color "nginx 已安装,请卸载后再安装" 1; exit ; }
cd ${SRC_DIR}
if [ -e ${NGINX_FILE} ${TAR} ];then
color "相关文件已准备好" 0http://nginx.org/download/
else
color '开始下载 nginx 源码包' 0
wget ${NGINX_URL} ${NGINX_FILE} ${TAR}
[ $? -ne 0 ] && { color "下载 ${NGINX_FILE} ${TAR} 文件失败" 1; exit ; }
fi
}
install () {
color "开始安装 nginx" 0
if id nginx &> /dev/null;then
color "nginx 用户已存在" 1
else
useradd -s /sbin/nologin -r nginx
color "创建 nginx 用户" 0
fi
color "开始安装 nginx 依赖包" 0
if [ `os_type` == "CentOS" -a `os_version` == '8' ] ;then
yum -y -q install make gcc-c++ libtool pcre pcre-devel zlib zlib-devel
openssl openssl-devel perl-ExtUtils-Embed
elif [ `os_type` == "CentOS" -a `os_version` == '7' ];then
yum -y -q install make gcc pcre-devel openssl-devel zlib-devel perl-ExtUtils-Embed
else
apt update &> /dev/null
apt -y install make gcc libpcre3 libpcre3-dev openssl libssl-dev zlib1g-dev &> /dev/null
fi
cd $SRC_DIR
tar xf ${NGINX_FILE} ${TAR}
NGINX_DIR=`echo ${NGINX_FILE} ${TAR} | sed -nr 's/^(.*[0-9]).*/\1/p' `
cd ${NGINX_DIR}
./configure --prefix=${NGINX_INSTALL_DIR} --user=nginx --group=nginx --with-http_ssl_module --with-http_v2_module --with-http_realip_module --with-http_stub_status_module --with-http_gzip_static_module --with-pcre --with-stream --with-stream_ssl_module --with-stream_realip_module
make -j $CPUS && make install
[ $? -eq 0 ] && color "nginx 编译安装成功" 0 || { color "nginx 编译安装失败,退出!" 1 ;exit ; }
echo "PATH=${NGINX_INSTALL_DIR} /sbin:${PATH} " > /etc/profile.d/nginx.sh
cat > /lib/systemd/system/nginx.service<<EOF
[Unit]
Description=The nginx HTTP and reverse proxy server
After=network.target remote-fs.target nss-lookup.target
[Service]
Type=forking
PIDFile=${NGINX_INSTALL_DIR}/logs/nginx.pid
ExecStartPre=/bin/rm -f ${NGINX_INSTALL_DIR}/logs/nginx.pid
ExecStartPre=${NGINX_INSTALL_DIR}/sbin/nginx -t
ExecStart=${NGINX_INSTALL_DIR}/sbin/nginx
ExecReload=/bin/kill -s HUP \$MAINPID
KillSignal=SIGQUIT
TimeoutStopSec=5
KillMode=process
PrivateTmp=true
[Install]
WantedBy=multi-user.target
EOF
systemctl daemon-reload
systemctl enable --now nginx &> /dev/null
systemctl is-active nginx &> /dev/null || { color "nginx 启动失败,退出!" 1 ;exit ; }
ln -sv /apps/nginx/sbin/nginx /usr/bin/
color "nginx 安装完成" 0
}
check
install
6.2 升级
6.2.1 平滑升级(不停机升级)
6.2.1.1 原理
编译新的nginx二进制文件,并启动,对老的进程发送信号使两个进程共存,但老进程会在每一个worker退出后关闭线程直到所有线程被关闭优雅退出,这时候由新worker全面接替,容器环境下直接打镜像即可,无需这么麻烦
7、命令管理
nginx -h
-V -v
-t
立刻停止服务:stop ,相当于信号SIGTERM,SIGINT
优雅的停止服务:quit ,相当于信号SIGQUIT
平滑重启,重新加载配置文件: reload,相当于信号SIGHUP
重新开始记录日志文件:reopen ,相当于信号SIGUSR1,在切割日志时用途较大
平滑升级可执行程序: 发送信号SIGUSR2,在升级版本时使用
优雅的停止工作进程: 发送信号SIGWINCH,在升级版本时使用
-s
-e
-c
8、配置
8.1 配置文件来源
nginx.conf
主配置文件include 定义的目录下的文件或文件
fastcgi uwsgi scgi
可以理解为自定义类型的配置文件
参考链接:https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Basics_of_HTTP/MIME_Types
8.2 配置文件格式
worker_processes 1;
events {
worker_connections 1024;
}
8.3 配置文件详解
8.3.1 主配置文件
# nginx.conf
主配置文件分四块
# 全局配置
默认以顶格写的配置
# 事件模块
event {
...
}
# http块
http {
...
}
# 用作负载的块
stream {
...
}
# mail 用的少
mail {
...
}
8.3.1.1 全局配置
user nginx nginx;
worker_processes 2;
worker_cpu_affinity 00000001 00000010;
error_log /apps/nginx/logs/error.log [debug | info | notice | warn | error | crit| alert | emerg]
pid /apps/nginx/run/nginx.pid
worker_priority 0;
worker_rlimit_nofile 65536;
* soft nofile 1000000
* hard nofile 1000000
* - nproc 1000000
daemon off;
include /etc/nginx/mime.types;
default_type application/octet-stream;
8.3.1.2 event块
event {
worker_connections 1024;
}
8.3.1.3 http块
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
use epoll;
accept_mutex on;
multi_accept on;
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 logs/access.log main;
tcp_nopush on;
tcp_nodelay off;
gzip on;
server_tokens on|off|build|string;
server {
listen 80;
server_name localhost;
charset utf-8;
access_log logs/host.access1.log main;
location / {
root html;
index index.html index.htm;
error_page 500 502 503 504 /50x.html;
error_page 401 402 403 404 /40x.html
}
location = /50x.html{
root html;
}
location = /40x.html{
root html;
}
}
}
9、web应用
9.1 修改nginx对外显示版本和名称
修改源码
/src/core/nginx.h
define NGINX_VERSION "1.68.9"
define NGINX_VER "gunginx/" NGINX_VERSION
修改配置
server_tokens on
9.2 做为web服务器
mkdir /apps/nginx/conf/conf.d
vim nginx.conf
http{
include /apps/nginx/conf/conf.d/*.conf
}
root@nginx1 nginx]
server {
listen 81;
server_name pc;
location / {
root html/pc;
index index_pc.html;
}
}
[root@nginx1 nginx]
html/
├── 40x.html
├── 50x.html
├── index.html
└── pc
└── index_pc.html
root@nginx1 nginx]
server {
listen 82;
server_name phone;
location / {
root html/phone;
index index_phone.html;
}
}
conf/conf.d/
├── pc.conf
└── phone.conf
html/
├── 40x.html
├── 50x.html
├── index.html
├── pc
│ └── index_pc.html
└── phone
└── index_phone.html
9.3 location 匹配规则
基于url的路径匹配,将文件与url进行映射,是web服务需要掌握的核心
参考资料
http://nginx.org/en/docs/http/ngx_http_core_module.html
9.3.1 语法
location [ = | ~ | ~* | ^~ ] uri { ... }
location = / {
[ configuration A ]
}
location ^~ / {
[ configuration A ]
}
location ~ / {
[ configuration A ]
}
location ~* / {
[ configuration A ]
}
location / {
[ configuration A ]
}
9.3.2 精准匹配(=)
server {
listen 81;
server_name pc;
location / {
root html/pc;
index index_pc.html;
}
location = /meihualu.jpg {
root /data/test;
}
}
../test
└── meihualu.jpg
9.3.3 正则开头(^~)
location ^~ /ima {
root /data/test;
}
../test
├── image1
└── meihualu.jpg
9.3.4 正则-不区分大小写(~)
location ~ /.*aoH.*.jpg {
root /data/test;
}
../test
├── image1
├── Laohu.jpg
└── meihualu.jpg
9.3.5 正则-区分大小写(~*)
location ~* /t.*i.jpg {
root /data/test;
}
../test
├── image1
├── Laohu.jpg
├── meihualu.jpg
└── TaiDi.jpg
9.3.6 匹配优先级
= > ^~ > ~/~* > /
9.4 基于四层的访问控制
location ~ /.*ao.*u.jpg {
root /data/test;
deny 172.31.3.1;
allow 172.31.3.0/24;
deny all;
}
[root@nexus ~]
HTTP/1.1 200 OK
Server: QianKun/v1.0
Date: Thu, 21 Dec 2023 05:33:31 GMT
Content-Type: image/jpeg
Content-Length: 1037344
Last-Modified: Thu, 21 Dec 2023 05:07:47 GMT
Connection: keep-alive
ETag: "6583c823-fd420"
Accept-Ranges: bytes
[root@nexus ~]
登出
Connection to 172.31.3.111 closed.
(base) gu@python:~/download$ curl 172.31.3.112:81/Laohu.jpg -I
HTTP/1.1 403 Forbidden
Server: QianKun/v1.0
Date: Thu, 21 Dec 2023 05:35:02 GMT
Content-Type: text/html
Content-Length: 153
Connection: keep-alive
9.5 基于账户密码认证
yum -y install httpd-tools
apt -y install apache2-utils
htpasswd -cb /apps/nginx/conf/.htpasswd gu 123456
location ~* /t.*i.jpg {
root /data/test;
auth_basic "login password" ;
auth_basic_user_file /apps/nginx/conf/.htpasswd;
}
9.6 自定义错误页面
error_page code ... [=[response]] uri;
error_page 404 403 402 401 /40x.html;
location = /40x.html {
root html;
}
9.7 自定义错误日志
error_log file [level];
level: debug, info, notice, warn, error, crit, alert, emerg
error_log /apps/nginx/logs/xx-error.log
9.8 文件检测
location / {
root /data/test;
index index.html;
try_files $uri $uri /index.html $uri .html /ss/default.html;
}
9.9 长连接配置
keepalive_timeout timeout [header_timeout]
keepalive_requests number;
9.10 下载服务器
需要ngx_http_autoindex_module模块
http://nginx.org/en/docs/http/ngx_http_autoindex_module.html
cd /usr/local/src/
./configure --help |grep autoindex
加上选项重新编译
autoindex on | off;
autoindex_exact_size on | off;
autoindex_localtime on | off ;
autoindex_format html | xml | json | jsonp;
limit_rate 100k;
location /download {
root /data/test;
autoindex on;
autoindex_exact_size off;
autoindex_localtime on;
}
9.11 状态页
需要ngx_http_stub_status_module模块
location = /status {
stub_status;
}
Active connections:
accepts:
handled:
requests:
Reading:
Writing:
Waiting:
9.12 第三方模块使用
git clone https://github.com/openresty/echo-nginx-module.git
--prefix=/apps/nginx --user=nginx --group=nginx --with-http_ssl_module --with-http_v2_module --with-http_realip_module --with-http_stub_status_module --with-http_gzip_static_module --with-pcre --with-stream --with-stream_ssl_module --with-stream_realip_module --without-http_autoindex_module --add-module=./echo-nginx-module
location = /echo {
index index.html;
default_type text/html;
echo "hello world,main-->" ;
echo $remote_addr ;
echo_reset_timer;
echo "took $echo_timer_elapsed sec for total." ;
}
9.13 nginx变量
9.13.1 内置变量
$remote_addr ;
$proxy_add_x_forwarded_for
$args ;
$document_root ;
$limit_rate ;
$remote_port ;
$remote_user ;
$request_body_file ;
$request_method ;
$request_filename ;
$request_uri ;
$scheme ;
$server_protocol ;
$server_addr ;
$server_name ;
$server_port ;
$http_ <name>
例子:
$http_user_agent ;
location = /echo {
index index.html;
default_type application/json;
echo_reset_timer;
echo "hello world,main-->" ;
echo "remote_addr" $remote_addr ;
echo "args" $args ;
echo "document_root" $document_root ;
echo "limit_rate" $limit_rate ;
echo "remote_port" $remote_port ;
echo "remote_user" $remote_user ;
echo "request_body_file" $request_body_file ;
echo "request_method" $request_method ;
echo "request_filename" $request_filename ;
echo "request_uri" $request_uri ;
echo "scheme" $scheme ;
echo "server_protocol" $server_protocol ;
echo "server_addr" $server_addr ;
echo "server_name" $server_name ;
echo "server_port" $server_port ;
echo "http_user_agent" $http_user_agent ;
echo "took $echo_timer_elapsed sec for total." ;
}
(base) gu@python:~/destop/github$ curl 172.31.3.112:81/echo
hello world,main-->
remote_addr 172.31.3.1
args
document_root /apps/nginx/html
limit_rate 0
remote_port 48218
remote_user
request_body_file
request_method GET
request_filename /apps/nginx/html/echo
request_uri /echo
scheme http
server_protocol HTTP/1.1
server_addr 172.31.3.112
server_name pc
server_port 81
http_user_agent curl/7.87.0
took 0.001 sec for total.
9.13.2 自定义变量
set $variable value;
server, location, if
location = /echo {
set $name guquanheng;
set $age 18;
......
echo "name" $name ;
echo "age" $age ;
echo "http_user_agent" $http_user_agent ;
echo "took $echo_timer_elapsed sec for total." ;
}
hello world,main-->
remote_addr 172.31.3.1
......
name guquanheng
age 18
http_user_agent Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 Edg/120.0.0.0
took 0.000 sec for total.
9.14 自定义日志格式(json)
# 简单来说就是将各种信息通过封装成json格式然后显示
# 配置日志格式
vim nginx.conf
log_format access_json
'{ "@timestamp" : "$time_iso8601" , '
'"host" : "$server_addr" , '
'"clientip" : "$remote_addr" , '
'"size" : $body_bytes_sent, '
'"responsetime" : $request_time, '
'"upstreamtime" : "$upstream_response_time" , '
'"upstreamhost" : "$upstream_addr" , '
'"http_host" : "$host" , '
'"uri" : "$uri" , '
'"xff" : "$http_x_forwarded_for" , '
'"referer" : "$http_referer" , '
'"tcp_xff" : "$proxy_protocol_addr" , '
'"http_user_agent" : "$http_user_agent" , '
'"status" : "$status" } ';
# 定义日志路径和日志格式名称
access_log /apps/nginx/logs/access_json.log access_json;
9.15 压缩功能
针对指定类型进行压缩传输,增加负载,节省带宽
依赖于模块 ngx_http_gzip_module
https://nginx.org/en/docs/http/ngx_http_gzip_module.html
可以配置在http,server,location
gzip on | off;
gzip_comp_level level;
gzip_min_length 1k;
gzip_http_version 1.0 | 1.1;
gzip_buffers number size;
gzip_types mime-type;
gzip_vary on ;
9.16 HTTPS实现
基于ngx_http_ssl_module模块
配置在 http 和 server
https://nginx.org/en/docs/http/ngx_http_ssl_module.html
vim nginx.conf
ssl on
listen 443 ssl;
ssl_certificate /path
ssl_certificate_key /path/to/file;
ssl_protocols [SSLv2] [SSLv3] [TLSv1] [TLSv1.1] [TLSv1.2];
ssl_session_cache off | none | [builtin [:size]] [shared:name:size];
off:
none:
builtin [:size]:
ssl_session_timeout time;
9.17 openssl版本升级
1、下载openssl源码
wget https://www.openssl.org/source/old/3.1/openssl-1.1.1w.tar.gz
2、重新编译安装,指定openssl源码路径
--with-openssl=
./configure --with-http_random_index_module --prefix=/apps/nginx --user=nginx --group=nginx --with-http_ssl_module --with-http_v2_module --with-http_realip_module --with-http_stub_status_module --with-http_gzip_static_module --with-pcre --with-stream --with-stream_ssl_module --with-stream_realip_module --add-module=./echo-nginx-module --with-openssl=/usr/local/src/openssl-1.1.1w
make -j 2 && make install
nginx -V
nginx version: nginx/1.20
built by gcc 4.8.5 20150623 (Red Hat 4.8.5-44) (GCC)
built with OpenSSL 1.1.1w 11 Sep 2023
TLS SNI support enabled
configure arguments: --with-http_random_index_module --prefix=/apps/nginx --user=nginx --group=nginx --with-http_ssl_module --with-http_v2_module --with-http_realip_module --with-http_stub_status_module --with-http_gzip_static_module --with-pcre --with-stream --with-stream_ssl_module --with-stream_realip_module --add-module=./echo-nginx-module --with-openssl=/usr/local/src/openssl-1.1.1w
9.18 Rewrite
https://nginx.org/en/docs/http/ngx_http_rewrite_module.html
配置在server和location块
9.18.1 if 指令
if (条件匹配) {
action
}
=
!=
~
!~
~*
!~*
-f
!-f
-d
-x
!-x
-e
location = /main {
if ($remote_addr = 172.31.3.111){
return 456;
}
}
[root@nexus ~]
HTTP/1.1 456
Server: nginx/1.20
Date: Fri, 22 Dec 2023 02:50:57 GMT
Content-Length: 0
Connection: keep-alive
9.18.2 set指令
参考9.13变量使用
9.18.3 break指令
location = /echo {
set $name guquanheng;
echo "name" $name ;
break ;
set $age 18;
echo "age" $age ;
index index.html;
default_type application/json;
echo_reset_timer;
echo "hello world,main-->" ;
echo "remote_addr" $remote_addr ;
echo "args" $args ;
echo "document_root" $document_root ;
echo "limit_rate" $limit_rate ;
echo "remote_port" $remote_port ;
echo "remote_user" $remote_user ;
echo "request_body_file" $request_body_file ;
echo "request_method" $request_method ;
echo "request_filename" $request_filename ;
echo "request_uri" $request_uri ;
echo "scheme" $scheme ;
echo "server_protocol" $server_protocol ;
echo "server_addr" $server_addr ;
echo "server_name" $server_name ;
echo "server_port" $server_port ;
echo "http_user_agent" $http_user_agent ;
echo "took $echo_timer_elapsed sec for total." ;
}
[root@nexus ~]
name guquanheng
age
hello world,main-->
remote_addr 172.31.3.111
args
document_root /apps/nginx/html
limit_rate 0
remote_port 16427
remote_user
request_body_file
request_method GET
request_filename /apps/nginx/html/echo
request_uri /echo
scheme http
server_protocol HTTP/1.1
server_addr 172.31.3.112
server_name pc
server_port 81
http_user_agent curl/7.29.0
took 0.000 sec for total.
9.18.4 return指令
return code;
return code text;
return code URL;
location = /echo {
set $name guquanheng;
echo "name" $name ;
return 345 "byebye" ;
set $age 18;
echo "age" $age ;
index index.html;
default_type application/json;
echo_reset_timer;
echo "hello world,main-->" ;
echo "remote_addr" $remote_addr ;
echo "args" $args ;
echo "document_root" $document_root ;
echo "limit_rate" $limit_rate ;
echo "remote_port" $remote_port ;
echo "remote_user" $remote_user ;
echo "request_body_file" $request_body_file ;
echo "request_method" $request_method ;
echo "request_filename" $request_filename ;
echo "request_uri" $request_uri ;
echo "scheme" $scheme ;
echo "server_protocol" $server_protocol ;
echo "server_addr" $server_addr ;
echo "server_name" $server_name ;
echo "server_port" $server_port ;
echo "http_user_agent" $http_user_agent ;
echo "took $echo_timer_elapsed sec for total." ;
}
[root@nexus ~]
* About to connect() to 172.31.3.112 port 81 (
* Trying 172.31.3.112...
* Connected to 172.31.3.112 (172.31.3.112) port 81 (
> GET /echo HTTP/1.1
> User-Agent: curl/7.29.0
> Host: 172.31.3.112:81
> Accept: */*
>
< HTTP/1.1 345
< Server: nginx/1.20
< Date: Fri, 22 Dec 2023 03:05:48 GMT
< Content-Type: application/json
< Content-Length: 6
< Connection: keep-alive
<
* Connection
byebye
9.18.5 rewrite_log指令
# 是否开启rewrite模块的日志
rewrite_log on ; # 开启后会记录在error 日志中,日志级别需要设置为notice
9.18.6 rewrite指令
rewrite regex replacement [flag];
[flag]
redirect;
permanent;
break ;
last;
9.19 盗链和防盗链
9.19.1 盗链
# 在页面插入其他网站的链接,当访问时会加载其他网站的信息
# 配置
<html >
<head >
<meta http-equiv =Content-Type content ="text/html;charset=utf-8" >
<title > 盗链</title >
</head >
<body >
<img src ="http://172.31.3.112:81/meihualu.jpg" >
<h1 style ="color:red" > hello</h1 >
</body >
</html >
9.19.2 防盗链
通过ngx_http_referer_module模块实现
配置在server和location
valid_referers none blocked server_names
*.example.com example.* www.example.org/galleries/
~\.google\.;
server_name pc.quanheng.com;
valid_referers none blocked server_names
*.quanheng.com ~\.jpg\. ;
if ($invalid_referer ){
return 403 "Forbidden Access" ;
}
10、负载均衡
10.1 七层负载
10.1.1 参数配置
1、proxy_pass http://172.31.3.112:81;
location /image {
proxy_pass http://172.31.3.112:81;
}
若location 匹配使用正则 那么proxy_pass后面的url不能带/
location ~|~* /image {
proxy_pass http://172.31.3.112:81;
}
2、proxy_hide_header {field};
3、proxy_pass_header {field};
4、proxy_pass_request_body on | off;
5、proxy_pass_request_headers on | off;
6、proxy_set_header;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for X-Real-IP $remote_addr ;
7、proxy_connect_timeout time;
8、proxy_read_timeout time;
9、proxy_send_timeout time;
10、proxy_http_version 1.0;
11、proxy_ignore_client_abort off;
10.1.2 缓存设置
1、proxy_cache zone_name | off; 默认off
zone_name
proxy_cache_path
/data/nginx/proxycache
inactive=120s
levels=1:1:2
keys_zone=proxycache:20m
max_size=1g;
2、proxy_cache_key string;
proxy_cache_key $scheme$proxy_host$request_uri ;
3、proxy_cache_valid [code ...] time;
proxy_cache_valid 404 1m;
proxy_cache_valid any 1m;
4、proxy_cache_methods GET | HEAD | POST ...;
10.1.3 添加响应首部字段
依赖ngx_http_headers_module模块
示例:
add_header X-Via $server_addr ;
add_header X-Cache $upstream_cache_status ;
add_header X-Accel $server_name ;
10.1.4 upstream模块
10.1.4.1 定义后端服务
upstream back_test1 {
server .....
......
}
upstream back_test1 {
server backend1.example.com weight=5 reslove;
server 127.0.0.1:8080 max_fails=3 fail_timeout=30s;
server unix:/tmp/backend3; max_conns=1
server backup1.example.com backup;
server 172.31.3.1 down;
hash KEY [consistent];
hash $request_uri consistent;
ip_hash;
least_conn;
}
10.1.4.2 使用
location /image {
proxy_pass http://back_test1;
}
10.2 四层负载
用lvs吧
11、参数优化
11.1 内核参数
fs.file-max = 1000000
net.ipv4.tcp_tw_reuse = 1
大,因为总有大量TIME_WAIT状态的链接存在
net.ipv4.tcp_keepalive_time = 600
效链接
net.ipv4.tcp_fin_timeout = 30
net.ipv4.tcp_max_tw_buckets = 5000
告信息,默认为8000,过多的TIME_WAIT套接字会使Web服务器变慢
net.ipv4.ip_local_port_range = 1024 65000
net.ipv4.tcp_rmem = 10240 87380 12582912
net.ipv4.tcp_wmem = 10240 87380 12582912
net.core.netdev_max_backlog = 8096
net.core.rmem_default = 6291456
net.core.wmem_default = 6291456
net.core.rmem_max = 12582912
net.core.wmem_max = 12582912
注意:以上的四个参数,需要根据业务逻辑和实际的硬件成本来综合考虑
net.ipv4.tcp_syncookies = 1
net.ipv4.tcp_max_syn_backlog = 8192
net.ipv4.tcp_tw_recycle = 1
net.core.somaxconn=262114
net.ipv4.tcp_max_orphans=262114
11.2 pam
/etc/security/limits.conf
* soft nofile 65535
* hard nofile 65535
* soft nproc 65535
* hard nproc 65535
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!