🪶山间笔记hillside notes

Nginx

55 分钟阅读 · 1.8w 字9 次浏览编辑

一、Nginx概述

Nginx (engine x) 是一个高性能的 HTTP 和 反向代理 服务,也是一个IMAP/POP3/SMTP服务。Nginx是由伊戈尔·赛索耶夫为俄罗斯访问量第二的Rambler.ru站点(俄文:Рамблер)开发的,第一个公开版本0.1.0发布于2004年10月4日。其将源代码以类BSD许可证的形式发布,因它的稳定性、丰富的功能集、示例配置文件和低系统资源的消耗而闻名。2011年6月1日,nginx 1.0.4发布。

Nginx是一款轻量级的Web 服务器/反向代理服务器及电子邮件(IMAP/POP3)代理服务器,并在一个BSD-like 协议下发行。其特点是占有内存少,并发能力强,事实上nginx的并发能力确实在同类型的网页服务器中表现较好,中国大陆使用nginx网站用户有:百度、京东、新浪、网易、腾讯、淘宝等。

在高连接并发的情况下,Nginx是Apache服务器不错的替代品。

二、为什么选择Nginx

2.1 Nginx特点

  1. 支持高并发,占用内存资源少

  2. 具有多种功能

  • Web服务功能

  • 均衡负载以及反向代理

  • 静态页面缓存

  • imap4/pop3邮件协议的反向代理

  • tcp/udp协议的请求转发(反向代理)

  1. 多平台支持

  2. Nginx的网络通信模型为异步网络IO模型:epoll模型

2.2 Nginx和Apache区别

2.2.1 内核和功能上的比较
特性 Nginx Apache
请求管理 事件驱动模型
使用异步套接字处理,较少了内存和CPU开销
同步套接字、进程和线程
每个请求都要使用一个单独的进程或线程,使用同步套接字
设计语言 C C、C++
可移植性 多平台 多平台
诞生时间 2002 1994
2.2.2 一般功能比较
功能 Nginx Apache
HTTPS支持 作为模块支持 作为模块支持
虚拟主机 原生支持 原生支持
CGI支持 仅支持FastCGI 支持CGI和FastCGI
系统模块 静态模块系统 动态模块系统

从以上功能上的对比,我们很难发现哪些功能Apache无法实现。那我们为什么更喜欢用Nginx 呢,Nginx 相对

Apache 有那些有点呢?

2.2.3 Nginx 相对 apache 的优点
  • 轻量级,同样起web 服务比Apache 占用更少的内存及资源

  • 静态处理,Nginx 静态处理性能比 Apache 高 3倍以上

  • 抗并发,Nginx 处理请求是异步非阻塞的,而Apache则是阻塞型的。在高并发下Nginx 能保持低资源低消耗高性能。在Apache+PHP(prefork)模式下,如果PHP处理慢或者前端压力很大的情况下,很容易出Apache进程数飙升,从而拒绝服务的现象。

  • 高度模块化的设计,编写模块相对简单

  • 社区活跃,各种高性能模块出品迅速

三、安装Nginx

3. 1 yum安装

配置yum源

[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

以上为官方repo源stable为稳定版本,mainline为新版本,下载时默认稳定版本,想要使用新版本,使用以下命令

yum-config-manager --enable nginx-mainline

[root@localhost ~]# yum clean all && yum makecache
[root@localhost ~]# yum -y install nginx

yum安装启动方式

[root@localhost ~]# systemctl start nginx
#启动
[root@localhost ~]# systemctl enable nginx
#设置开机自启

3. 2 源码编译

依赖关系:openssl-devel pcre-devel

(1) 创建运行nginx服务的用户 

[root@localhost ~]# useradd  --system -M -s /sbin/nologin  nginx

(2) 解压nginx

[root@localhost lnmp]# tar -zxf nginx-1.19.4.tar.gz

(3) 配置nginx编译环境(参数指定openssl等时指定其源码包)

[root@localhost nginx-1.18.0]# ./configure --prefix=/apps/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

(4) 编译安装nginx

[root@localhost nginx-1.19.4]# make && make install

(5) 修改nginx安装目录权限所有者

[root@localhost local]# chown -R nginx:nginx /usr/local/nginx/

(6) 编辑nginx服务配置文件/usr/local/nginx/conf/nginx.conf ,修改nginx服务启动的默认用户为nginx

[root@localhost nginx]# vim /usr/local/nginx/conf/nginx.conf 

(7) 启动nginx

[root@localhost nginx]# /usr/local/nginx/sbin/nginx

(8) 查看nginx是否启动成功

[root@localhost nginx]# ps aux|grep nginx

​ (9) 添加nginx启动到systemctl

[root@www ~]# vim /usr/lib/systemd/system/nginx.service
[Unit]
Description=nginx - high performance web server
Documentation=http://nginx.org/en/docs/
After=network-online.target remote-fs.target nss-lookup.target
Wants=network-online.target

[Service]
Type=forking
PIDFile=/apps/nginx/logs/nginx.pid
ExecStart=/apps/nginx/sbin/nginx -c /apps/nginx/conf/nginx.conf
ExecReload=/bin/sh -c "/bin/kill -s HUP $(/bin/cat /apps/nginx/logs/nginx.pid)"
ExecStop=/bin/sh -c "/bin/kill -s TERM $(/bin/cat /apps/nginx/logs/nginx.pid)"

[Install]
WantedBy=multi-user.target

(10)编译失败总结

checking for uint32_t ... uint32_t not found, u_int32_t not found
./configure: error: can not define uint32_t
# 编译时出现以上错误执行以下命令解决
[root@localhost ~]# yum -y install kernel-headers kernel-devel

3. 3 相关文件目录

此为yum方式安装。源码安装需自定义。

/usr/share/nginx/html #默认网页站点目录

/etc/nginx/nginx.conf #主配置文件

/etc/nginx/conf.d/default.conf #默认网站配置文件

------------------------------------------------------nginx代理相关参数文件------------------------------------------------------

/etc/nginx/fastcgi_params #php代理文件

/etc/nginx/scgi_params #AJAX前后分离

/etc/nginx/uwsgi_params #Python代理文件

------------------------------------------------------nginx编码相关参数文件------------------------------------------------------

/etc/nginx/win-utf #Nginx编码转换映射文件

/etc/nginx/koi-utf #Nginx编码转换映射文件

/etc/nginx/koi-win #Nginx编码转换映射文件

------------------------------------------------浏览器支持的直接打开的文件格式------------------------------------------------

/etc/nginx/mime.types

------------------------------------------------------nginx管理相关命令------------------------------------------------------

/usr/sbin/nginx #Nginx命令行管理终端工具

/usr/sbin/nginx-debug #Nginx命令行与终端调试工具

------------------------------------------------------nginx日志相关目录与文件------------------------------------------------------

/var/log/nginx #Nginx默认存放日志目录

/etc/logrotate.d/nginx #Nginx默认的日志切割/usr/sbin/nginx #Nginx命令行管理终端工具

/usr/sbin/nginx-debug #Nginx命令行与终端调试工具

3. 4 Nginx控制方式

[root@localhost ~]# systemctl start nginx

[root@localhost ~]# nginx -s reload|stop

3.5 vim编辑ngxin配置文件高亮

源码编译默认vim打开nginx的配置文件没有高亮显示,nginx官方源码中自带了vim的高亮显示。

[root@localhost nginx-1.19.4]# cp -rf contrib/vim/* /usr/share/vim/vimfiles/

这样打开nginx配置文件后,对应关键字就会以高亮显示。

四、默认配置文件详解

4. 1 nginx.conf详解

user nginx; -------------------------------运行程序的用户

worker_processes 1; ---------工作线程数量。一般情况默认1即可。如出现502等,可设置为CPU核心数量。新版本支持auto,可自动选择worker进程数量。

error_log /var/log/nginx/error.log warn; ----------错误日志文件路径

pid /var/run/nginx.pid; -------------------pid文件路径

events {

worker_connections 1024; -------------------一个工作线程最大连接数量

}

http { ------------------------------------------http区域

include /etc/nginx/mime.types; ----------加载配置文件,mine.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; 
#简单说,sendfile是个比 read 和 write 更高性能的系统接口, 不过需要注意的是,sendfile 是将 in_fd 的内容发送到 out_fd 。而 in_fd 不能是 socket , 也就是只能文件句柄。 所以当 Nginx 是一个静态文件服务器的时候,开启 SENDFILE 配置项能大大提高 Nginx 的性能。 但是当 Nginx 是作为一个反向代理来使用的时候,SENDFILE 则没什么用了,因为 Nginx 是反向代理的时候。 in_fd 就不是文件句柄而是 socket,此时就不符合 sendfile 函数的参数要求了

#tcp_nopush on;-----------开启可以确保在发送到客户端之前数据包已经充分“填满”, 这大大减少了网络开销,并加快了文件发送的速度
#tcp_nodelay on/off;------开启后nginx
keepalive_timeout 65; ----------------------------超时时间
#gzip on;
include /etc/nginx/conf.d/*.conf;
}

4. 2 default.conf详解

server { ---------------------------------------指定一个虚拟主机

    listen 80; ----------------------------指定监听端口

    server_name localhost; -----------------指定域名

    #charset koi8-r;

    #access_log /var/log/nginx/host.access.log main; ----指定日志文件

    location / { ---------------------------------此处对应根目录为站点目录(URI目录)

        root /usr/share/nginx/html; -------------指定网站站点目录

        index index.html index.htm; -------------指定解析网站的站点首页类型

    }

    #error_page 404 /404.html; -------指定404状态码页面

    # redirect server error pages to the static page /50x.html

    error_page 500 502 503 504 /50x.html;

    location = /50x.html {

    root /usr/share/nginx/html;
    }

    # proxy the PHP scripts to Apache listening on 127.0.0.1:80

    #

    #location ~ .php$ { ----------------指定反向代理

        # proxy_pass http://127.0.0.1;

    #}

    # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000

    #

    #location ~ .php$ { ----------------------指定php解析

        # root html;

        # fastcgi_pass 127.0.0.1:9000;

        # fastcgi_index index.php;

        # fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;

        # include fastcgi_params;

    #}

    # deny access to .htaccess files, if Apache's document root

    # concurs with nginx's one

    #

    #location ~ /.ht {

        # deny all;

    #}
#}

五、Nginx其他配置详解

5.1 全局配置

daemon off;
Nginx默认为后台运行,在调试等时可以使用以上参数关闭后台,以前台运行。
master_process off|on;
Nginx是否开启master-worker模式。默认为on。

5.2 events语句块

worker_connections 10240;
设置单个进程的最大并发连接数,此值设置最好worker_connections*CPU核心数等于worker_rlimit_nofile
use epoll;
使用epoll事件驱动
accept_mutex on;
当为on时,在一个新的请求过来时,如有4个worker在休眠,就只会唤醒一个worker进行处理,每个新的请求过来时单独唤醒一个进行处理。为off时,当有一个新的请求过来时,将会唤醒所有的worker进程,然后worker进程之间竞争处理新的请求。建议此值设置为on。
multi_accept off;
为on时nginx服务器的每个工作进程可以同时接受多个新的网络连接。为off时一个工作进程只能接受一个新的网络连接。建议设置为on。

5.3 http配置块

http协议配置说明

include mime.types;
#导入支持的文件配型,此路径为相对于Nginx安装目录,可绝对路径。mime可支持图片、php、视频等。此选项类似于说是nginx访问时的资源类型,是图片还是视频等。
sendfile          on;      # 用于开启文件高效传输模式,一般设置为on,若nginx是用来进行磁盘IO负载应用时,可以设置为off,降低系统负载
tcp_nopush        on;      # 减少网络报文段数量,当有数据时,先别着急发送, 确保数据包已经装满数据, 避免了网络拥塞
tcp_nodelay       on;      # 提高I/O性能,确保数据尽快发送, 提高可数据传输效率   
gzip              on;      # 是否开启 gzip 压缩 
types_hash_max_size 2048;  # 影响散列表的冲突率。types_hash_max_size 越大,就会消耗更多的内存,但散列key的冲突率会降低,检索速度就更快。 
#types_hash_max_size越小,消耗的内存就越小,但散列key的冲突率可能上升
default_type application/octet-stream;
#在Nginx访问时如出现没有定义的非图片视频等的文件类型时的默认文件类型,默认会将此文件识别为二进制文件进行下载。可修改为其他类型进行展示。如Nginx默认不支持PHP文件,在站点目录下创建index.php后访问此文件会下载此文件。如果修改为default_type text/plain;后会将其展示为txt的文本类型。
server_tokens on|off|build|string;
#设置响应报文头的server类型。默认会显示服务器上的nginx版本,此不安全,可将其隐藏。在商业版Nginx1.9以上版本可自定义此字段。社区版本没有此功能,但是可以在编译安装时修改此值,在源码目录下/opt/nginx-1.18.0/src/core/nginx.h,修改一下两个地方,在server_tokens on时会显示这个文件修改的值。
define NGINX_VERSION      "1.18.0"
define NGINX_VER          "nginx/" NGINX_VERSION
#另外还需修改/opt/nginx-1.18.0/src/http/ngx_http_header_filter_module.c,在server_tokens of
#f时会显示这个文件修改的值。
static u_char ngx_http_server_string[] = "Server: nginx" CRLF;
#然后在重新编译,然后把编译好的nginx可执行文件复制过去即可。
root html;
指定站点根目录,可放在http、server、location、if in location
location / {
    root /apps/nginx/html;
}
location /about {
    root /apps/nginx/html/;必须有在此root下有about目录,否则报404错误。
}
与其相似的指令
alias (alias只能放在location中)
location /about {  #在/about后不要加/,使用alias的时候如果后面加了/,则下面的路径配置必须加/,否则403错误
    alias /apps/nginx/html/about;#当访问about时,会显示alias定义的/usr/share/nginx/html/about的内容。
}

5.4 server语句块

listen      80;        # 设置监听的端口 
server_name  localhost;        # 设置绑定的主机名、域名或ip地址 
charset koi8-r;
#设置显示的默认字符集类型。设置编码字符

5.5 location语句块

5.5.1 location匹配优先级
#在locaiton中的为局部指令
语法:location [ = | ~ | ~* | ^~ ] uri {...}
location匹配优先级
location = xx   #精确匹配 优先级1。访问的uri必须与xx一样,并且区分大小写,才能匹配。
location ^~ xxx #优先匹配 优先级2。表示包含正则表达式,并且匹配以指定正则开头
location ~       #区分大小写匹配 优先级3
location ~*      #不区分大小写 优先级3
location uri     #根据uri进行匹配 优先级3
location /       #默认匹配 优先级最低

5.6 Nginx虚拟主机配置

5.6.1 Nginx创建一个web站点
5. 6.1.1 编写一个虚拟主机配置文件
[root@localhost conf.d]# vim /etc/nginx/conf.d/www.conf
server {
    listen 80;
    server_name www.test.com;
    location / {
        root /usr/share/nginx/www;
        index index.html;
    }
}
5. 6.1.2 创建站点目录以及站点主页文件
[root@localhost conf.d]# mkdir /usr/share/nginx/www
[root@localhost conf.d]# echo "123" > /usr/share/nginx/www/index.html
5. 6.1.3 测试

浏览器输入 ip地址或站点域名(提前搭建DNS或修改Hosts文件解析域名)测试访问

{width="4.124484908136483in" height="0.9894597550306212in"}

5.6.1.4 企业环境web虚拟主机访问方式

a. 基于域名的访问方式

b. 基于地址的访问方式(安全,只能指定地址访问)--负载均衡 高可用

server {
    listen 192.168.100.100:80;
    server_name www.test.com;
    location /www {
        root /usr/share/nginx/www;
        index index.html;
    }
}

c. 基于端口访问

5.6.2 Nginx编写多站点
5.6.2.1 编写多个虚拟主机配置文件
[root@localhost ~]# vim /etc/nginx/conf.d/www.conf
server {
    listen 80;
    server_name www.test.com;
    location / {
        root /usr/share/nginx/www;
        index index.html;
    }
}
[root@localhost ~]# vim /etc/nginx/conf.d/cn.conf
server {
    listen 80;
    server_name www.test.cn;
    location /cn {
        root /usr/share/nginx/html;
        index index.html;
    }
}
5.6.2.2 创建站点目录以及站点主页文件
[root@localhost ~]# mkdir /usr/share/nginx/www
[root@localhost ~]# echo "123" > /usr/share/nginx/html/www/index.html
[root@localhost ~]# mkdir /usr/share/nginx/cn
[root@localhost ~]# echo "123" > /usr/share/nginx/html/cn/index.html
5.6.2.3 测试

浏览器输入 ip地址或站点域名(提前搭建DNS或修改Hosts文件解析域名)测试访问

{width="4.124484908136483in" height="0.9894597550306212in"}

{width="3.7182852143482066in" height="0.9061362642169729in"}

5.7 Nginx四层访问控制(IP禁止)

访问控制基于模块ngx_http_access_module实现,可以用过匹配客户端源IP地址进行限制。可以作用于

http、server、location、limit_except

注意:如果能在防火墙设备控制,最好不要在nginx上配置,可以节约资源。

范例:

server {
    listen 80;
    server_name www.test.com;
    deny 192.168.100.100;
    allow 192.168.100.200;
    deny 192.168.100.0/24;
    location / {
        root html;
        index index.html index.htm;
    }
}

编写deny、allow规则,小范围的在上,大范围在下。

5.8 Nginx账户认证功能

由ngx_http_auth_basic_module模块提供此功能。

范例:

#Centos安装包
[root@localhost conf.d]# yum -y install httpd-tools
#创建用户,-b 非交互式方式提交密码
[root@localhost conf.d]# htpasswd -cb /apps/nginx/conf/.htpasswd user1 123456
Adding password for user user1
[root@localhost conf.d]# htpasswd -b /apps/nginx/conf/.htpasswd user2 123456
Adding password for user user2
[root@localhost conf.d]# cat /apps/nginx/conf/.htpasswd
user1:$apr1$RjmOu2Kr$VHvkAIc5OYg.3ZoaGwaGq/
user2:$apr1$nIqnxoJB$LR921DTJT.viDJhXa6wHv.

[root@localhost ~]# vim /apps/nginx/conf/conf.d/www.conf 
    location = /login/ {
        root /apps/nginx/html/login;
        index index.html index.htm;
        auth_basic              "login password";
        auth_basic_user_file     /apps/nginx/conf/conf.d/.htpasswd;
    }

5.9 自定义错误页面

定义错误页面,以指定的响应状态码进行响应,可生效区域:http、server、location、if in location

语法:

error_page code ...[=[response]] uri;

范例:

error_page 500 502 503 504 /error.html;
location /error.html {
    root /opt;
}
#重启Nginx并访问不存在的页面进行测试

范例:

error_page 404  /index.html;
location /index.html {
    root /apps/nginx/html;
}
#如果是404就跳转返回到主页面

范例:防止360等垃圾浏览器劫持错误页面显示

类似360浏览器,在访问时如果访问不存在页面,应该返回服务器的错误页面,但是浏览器进行了劫持,显示了插入广告的360错误页面。可通过修改返回的错误码方式防止。

error_page 404 =302 /error.html;
location /error.html {
    root /opt;
}

5.10 自定义错误日志

语法:

Syntax:	error_log file [level];
Default:	
error_log logs/error.log error;
Context:	main, http, mail, stream, server, location
level :debug, info, notice, warn, error, crit, alert, emerg

范例:

[root@localhost ~]# touch /apps/nginx/logs/test_error.log
#自定义错误日志文件位置
[root@localhost ~]# vim /apps/nginx/conf/conf.d/www.conf
server {
    listen 80;
    server_name www.test.com;
    access_log  logs/host.access.log  main;
    error_log  logs/error.log  notice;
}

5.11 检测文件是否存在

try_files会按顺序检测文件是否存在,返回第一个找到的文件或文件夹(结尾加斜线表示为文件夹),如果所有文件或文件夹都找不到,会进行一个内部重定向到最后一个参数。只有最后一个参数可以引起一个内部重定向,之前的参数只设置内部URI的执向。最后一个参数是回退URI且必须存在,否则会出现内部500错误。

范例:

location / {
    root /apps/nginx/html;
    index index.html index.htm;
    try_file $uri $uri.html $uri/index.html /about/default.html;
    #try_file $uri $uri.html $uri/index.html =489  将找不到的页面返回一个489的自定义状态码
}
#当访问URL时,会先在try_file中寻找有没有此文件,没有的话会匹配最后一个/about/default页面(此页面必须存在,否则报500错误),如果是自定义的状态码会返回状态码

5.12 长连接配置

语法:

keepalived_timeout timeout [header_timeout]; #设置保持连接超时时长,0表示禁止长连接,默认为65s,通常配置在http字段作为站点全局配置
keepalived_requests number; #在一次长连接上所允许请求的资源的最大数量,默认为100次,建议适当调大,比如500。

范例:

keepalived_requests 3;
keepalived_timeout 65 60;
#开启长连接后,返回客户端的会话保持时间为60s,单次长连接累计请求到达指定次数请求或65s就会被断开,后面的60为发送给客户端应答报文头部中显示的超时时间设置为60s。如不设置客户端将不显示超时时间。

#如果设置的header_timeout,浏览器则会收到服务器的报文
Keep-Alive:timeout=60

#如果设置为0,浏览器则会收到服务器的报文
Connecton:close

5.13 Nginx作为下载服务器配置

ngx_htttp_autoindex_module模块处理以斜线字符"/"结尾的请求,并生成目录列表,可以作为下载服务配置使用

语法:

autoindex on|off; #自动文件索引功能,默认为off
autoindex_exact_size on|off; #计算文件确切大小(单位bytes),off显示大概大小(单位K、M),默认为on
autoindex_localtime on|off; #显示本机时间而非GMT(格林威治)时间,默认为off
autoindex_format html|xml|json|jsonp; #显示索引的页面文件风格,默认html
limit_rate rate; #限制响应客户端传输速率(除GET和HEAD以外的所有方法),单位B/s,即bytes/second,默认为0,表示无限制,此指令由ngx_http_core_module提供

范例:

#做为下载服务不需要index.html
[root@localhost ~]# mkdir /apps/nginx/html/centos
#创建下载目录

[root@localhost download]# vim /apps/nginx/conf/conf.d/www.conf
location /centos {
    autoindex on;
    autoindex_exact_size on;
    autoindex_localtime on;
    limit_rate 1024k;
    root html;
}
#重启Nginx,访问http://www.test.com/centos即可

5.14 Nginx作为上传服务器配置

语法:

client_max_body_size 1m; #设置允许客户端上传单个文件的最大值,默认值为1m,上传文件超过此值会出413错误码
client_body_buffer_size size; #用于接收每个客户端请求报文的body部分的缓冲区大小;默认16k;超出此大小时,其将被暂存到磁盘上,磁盘上的位置由下面 client_body_temp_path指令所定义的位置
client_body_temp_path path [level1 [level2 [level3]]];
#设定存储客户端请求报文的body部分的临时存储路径及子目录结构和数量,目录名为16制的数字,使用hash之后的值从后往前截取1位、2位、2位作为目录名

范例:

[root@localhost ~]# md5sum /apps/nginx/html/upload/index.html
 95f6f65f498c74938064851b1bb 96 3d 4 /apps/nginx/html/upload/index.html
1级目录占1位16进制,即2^4=16个目录 0-f
2级目录占2位16进制,即2^8=256个目录 00-ff
3级目录占2位16进制,即28=256个目录 00-ff

#配置示例:
 client_max_body_size 100m; #如果太大,上传时会出现下图的413错误,注意:如果php上传,还需要修改php.ini的相关配置
 client_body_buffer_size 1024k;
 client_body_temp_path /apps/ngnx/client_body_temp/ 1 2 2;#上传时, Nginx会自动创建相关目录
#上传文件后,会自动自动生成相关目录
[root@localhost ~]# tree /apps/nginx/html/upload/
/apps/nginx/html/upload/
└── 5
│   └── 00          
│         └── 00
└── 6 
      └── 00
            └── 00

5.15 Nginx其他配置

Keepalive_disable none|browser ...;
#对哪种浏览器禁用长连接
limit_except method ...{...},仅用于location
#限制客户端使用除了指定的请求方式之外的其他方法
method: GET, HEAD, POST, PUT, DELETE, MKCOL COPY, MOVE, OPTIONS, PROPFIND, PROPPATCH, LOCK,UNLOCK, PATCH
limit_except GET {
    allow 192.168.0.0/24;
    allow 10.0.0.1;
    deny all;
}
aio on|off #是否启用 asynchronous file I/O(aio)功能,需要编译开启--with-file-aio

#linux2.6以上内核提供以下几个系统调用来支持aio:
1、sys_io_setup:建立aio的 context
2、sys_io_submit:提交I/0操作请求
3、sys_io_getevents:获取已完成的I/o事件
4、sy_io_cancel1:取消/0操作请求
5、sys_io_destroy:毁销aio的 context
 directio size|off; #操作完全和aio相反,aio是读取文件而directio是写文件到磁盘,启用直接I/O,默认为关闭当文件大于等于给定大小时,例如:directio 4m;同步(直接)写磁盘,而非写缓存。
open_file_cache off; #是否缓存打开过的文件信息
open_file_cache max=N [inactive=time];

#nginx可以缓存以下三种信息:
(1)文件元数据:文件的描述符、文件大小和最近一次的修改时间
(2)打开的目录结构
(3)没有找到的或者没有权限访问的文件的相关信息

max=N:#可缓存的缓存项上限数量;达到上限后会使用LRU(Least recently used,最近最少使用)算法实现管理
inactive=time:#缓存项的非活动时长,在此处指定的时长内未被命中的或命中的次数少于 open_file_cache_min_uses指令所指定的次数的缓存项即为非活动项,将被删除

open_file_cache_valid time; #缓存项有效性的检查验证频率,默认值为60s
open_file_cache_errors on|off;# 是否缓存查找时发生错误的文件一类的信息,默认值为off
open_file_cache_min_uses number; #open_file_ cacheinactive指令的参数指定的时长内,至少被命中此处指定的次数方可被归类为活动项,默认值为1

六、Nginx高级配置

6.1 Nginx状态统计模块

Nginx的状态统计基于nginx的状态模块,如在编译安装nginx时需开启status模块

[root@localhost nginx-1.19.4]# ./configure --with-http_stub_status_module

确定开启status状态模块后,在对应server区域内添加开启状态模块,最好加验证模块

location /status {
    stub_status on;
    access_log off;
    auth_basic  "auth login";
    auth_basic_user_file /apps/nginx/conf/.htpasswd;
    allow 192.168.100.0/24;
    allow 127.0.0.1;
    deny all;
}
[root@localhost conf.d]# systemctl restart nginx

重启测试访问

Active connections: 1  
server accepts handled requests
 1 1 1 
Reading: 0 Writing: 1 Waiting: 0 

Active connections: #当前处于活动状态的客户端连接数,包括连接等待空闲连接数=reading+writing+waiting
accepts: #统计总值, Nginx自启动后已经接受的客户端请求的总数。
handled: #统计总值, Nginx自启动后已经处理完成的客户端请求总数,通常等于 accepts,除非有因workerconnections限制等被拒绝的连接
requests: #统计总值, Nginx自启动后客户端发来的总的请求数。
Reading: #当前状态,正在读取客户端请求报文首部的连接的连接数,数值越大,说明排队现象严重,性能不足
Writing: #当前状态,正在向客户端发送响应报文过程中的连接数,数值越大,说明访问量很大
Waiting: #当前状态,正在等待客户端发出请求的空闲连接数,开启keep-alive的情况下,这个值等于active-(reading+writing)
6.1.1 取状态页值
[root@localhost ~]# curl www.test.com/status 2>/dev/null |awk '/Reading/{print $2,$4,$6}'

可使用脚本检查或添加到zabbix自定义监控中

6.2 Nginx第三方模块

第三模块是对 nginx的功能扩展,第三方模块需要在编译安装 Nginx的时候使用参数--add-module=PATH指定路径添加,有的模块是由公司的开发人员针对业务需求定制开发的,有的模块是开源爱好者开发好之后上传到 github进行开源的模块, nginx支持第三方模块需要从源码重新编译支持,比如开源的echo模块ttps: echo https://github.com/openresty/echo-nginx-module

[root@localhost opt]# git clone https://github.com/openresty/echo-nginx-module.git
#下载源代码
[root@localhost opt]# cd nginx-1.18.0/
#进入nginx源代码目录
[root@localhost nginx-1.18.0]# nginx -V
nginx version: testnginx/1
built by gcc 4.8.5 20150623 (Red Hat 4.8.5-44) (GCC) 
built with OpenSSL 1.0.2k-fips  26 Jan 2017
TLS SNI support enabled
configure arguments: --prefix=/apps/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
#查看原有编译选项
[root@localhost nginx-1.18.0]# ./configure --prefix=/apps/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=/opt/echo-nginx-module
#使用--add-module=PATH 添加指定模块
[root@localhost nginx-1.18.0]# make && make install
#重新编译安装
[root@localhost nginx]# vim /apps/nginx/conf.d/www.conf
    location /echo {
        index index.html;
        default_type test/html;
        echo "hello world-->>>\n";
        echo "this is remote port\n";
        echo $remote_port;
    }   
重启Nginx访问
[root@localhost ~]# curl www.test.com/test
hello world-->>> this is remote port 51526
#echo模块可以用来打印变量,方便查询变量含义

6.3 Nginx变量

nginx的变量可以在配置文件中引用,作为功能判断或者日志等场景使用

变量可以分为内置变量和自定义变量

内置变量是由 nginx模块自带,通过变量可以获取到众多的与客户端访问相关的值。

6.3.1 Nginx内置变量
6.3.1.1 常用内置变量
$remote_addr;
#存放了客户端的地址,注意是客户端的公网IP

$proxy_add_x_forwarded_for
#此变量表示将客户端IP追加请求报文中x-Forwarded-for首部字段,多个IP之间用逗号分隔,如果请求中没有x-Forwarded--for,就使用$remote_addr
the "X-Forwarded-For" client request header field with the Sremote_addr variable appended to it, separatedby comma. If the "X-Forwarded-For" field is not present in the client request header, the $proxy_add_x_forwarded_for variable is equal to the Sremote_addr variable.
 
$args;
#变量中存放了URL中的参数,例如:http://www.test.com/main/index.do?id=20190221&partner=search
#返回结果为:id=20190221&partner=search中的id=20190221&partner=search

$document_root;
#保存了针对当前资源的请求的系统根目录,例如:/apps/nginx/html

$document_uri;
#保存了当前请求中不包含参数的URI,注意是不包含请求的指令,比如 #URI http: //www. magedu.org/main/index. do?id=20190221&partner=sear ch会被定义为/main/index.do
#返回结果为:/main/index.do

$host
#存放了请求的主机名(host名)

limit_rate 10240;
echo $limit_rate;
#如果nginx服务器使用limit_rate配置了显示网络速率,则会显示,如果没有设置,则显示0

$remote_port;
#客户端请求nginx服务器时随机打开的端口,这是每个客户端自己的端口

$remote_user;
#已经经过auth basic module验证的用户

$request_body_file;
#做反向代理时发给后端服务器的本地资源的名称

$request_method;
#请求资源的方式,GET/POST等

$request_filename;
#当前请求的资源文件的磁盘路径,由root或alias指令与URI请求生成的文件绝对路径,如:/apps/nginx.html/main/index.html

$request_uri
#包含请求参数的原始URI,不包含主机名,相当于:$document_uri?$args,例如:/main/index.do?id=20190221&partner=search

$scheme;
#请求的协议,例如:http、https、ftp等

$server_protocol
#保存了客户端请求资源使用的协议的版本,例如:HTTP/1.0,HTTP/1.1,HTTP/2.0等

$server_addr;
#保存了服务器的ip地址

$server_name;
#请求的服务器的主机名

$server_port;
#请求的服务器的端口号

$http_<name> 
#name为任意请求报文首部字段,表示记录请求报文的首部字段。例如http_User_Agent,http_host等,在请求报文中的首部字段

$http_user_agent;
#客户端浏览器的详细信息

$http_cookie;
#客户端的cookie信息

$cookie_<name>
#name为任意请求报文首部字段cookie的key名
6.3.1.2 自定义变量

语法:

Syntax:set $variable value;
Default: -
Context: server,location,if

范例:

set $name Godyang;
echo $name;
set $my_port $server_port;
echo $my_port;
#前面为变量名称 后面为自定义值,也可以是Nginx的内置变量

#测试
[root@localhost ~]# curl www.test.com/test
Godyang
80

6.4 Nginx自定义访问日志

访问日志是记录客户端即用户的具体请求内容信息,全局配置模块中的 error_log是记nginx录服务器运行时的日志保存路径和记录日志的 level,因此有着本质的区别,而且 Nginx的错误日志一般只有一个,但是访问日志可以在不server中定义多个,定义一个日志需要使用 access_log指定日志的保存路径,使用 log_format指定日志的格式,格式中定义要保存的具体日志内容。

访问日志由ngx_http_log_module模块实现

语法:

Syntax:	access_log path [format [buffer=size] [gzip[=level]] [flush=time] [if=condition]];
access_log off;
Default:	
access_log logs/access.log combined;
Context:	http, server, location, if in location, limit_except
6.4.1 自定义默认格式日志

如果是要保留日志的源格式,只是添加相应的日志内容,则配置如下:

注意:log_format只能在http语句块定义生效,access_log可针对其他语句块生效

log_format nginx_format1 '$remote_addr - $remote_user [$time_local] "Srequest"'
                         '$status $body_bytes_sent "$http_referer" '
                         '"$http_user_agent" "$http_x_forwarded_for"'
                         '$server-name: $server-port';
access_log logs/access. log nginx_format1;

#重启nginx并访问测试日志格式
 ==>/apps/nginx/logs/access. log <=
 10.0.0.1--[22/Feb/2019: 08: 44: 14 +0800  ico HTTP/1. 1" 404 162 "_" "Mozilla/5.0 (windows NT
6.1;win64;x64;rv:65.0)Gecko/2
 0100101 Firefox/65.0""-"www.test.com: 80
6.4.2 自定义json格式日志

Nginx的默认访问日志记录内容相对比较单一,默认的格式也不方便后期做日志统计分析,生产环境中通常将 nginx日志转换为json日志,然后配合使用ELK做日志收集-统计-分析。

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;

#重启 #nginx, : http: //json. cn/并访问测试日志格式,参考链接http://json.cn/
{"@timestamp": "2021-03-31T02:27:37-04:00","host": "192.168.100.103","clientip": "192.168.100.101","size": 612,"responsetime": 0.000,"upstreamtime": "-","upstreamhost":"-","http_host": "www.test.com","uri": "/index.html","xff": "-","referer": "-","tcp_xff": "-","http_user_agent": "curl/7.29.0",status": "200"}
6.4.3 json格式的日志访问统计
#python3
[root@centos8 ~]#cat log.py
#!/usr/bin/env python3
#coding: utf-8

status_200 = []
status_404 = []
with open("access_json.log") as f:
    for line in f.readlines():
        line = eval(line)
        if line.get("status") == "200":
            status_200.append(line. get)
        elif line.get("status")=="404":
            status_404.append(line. get)
        else:
            print(状态码ERROR")
        print((line. get ("clientip")))
f.closeO

print("状态码200的有--:",len(status_200))
print("状态码404的有--:",len(status_404))I
6.4.4 日志切割

若记录了Nginx 的access Log,最好能够按天对日志进行切割、压缩。这样做的好处有: - 日志归档清晰 - 大量的日志也不会导致磁盘空间占满 - 若当天业务有问题,查询日志时不必从历史日志出发

#!/bin/bash
# 脚本功能
# 定期删除30天一天的归档日志。
# 可以通过crontab 在每天凌晨后执行, 执行后会将前一天的日志归档到 $LOGARCHIVE 变量指定的目
录中
# 可以留作业, 让学生改进成,每天归档后对日志进行压缩。以减少日志对磁盘的使用情况。
# 日志被 mv 走后, 对 Nginx 发送了 -USR1 信号, 重新打开日志文件。 这个在第一章中有介绍
# Nginx 日志存放目录
LOGDIR="/data0/www/logs"
# 一定要设置Nginx 的 access log 日志文件后缀名都为 -access_log
LOGSUFFIXA="*-access_log"
# 归档日志存放的目录
LOGARCHIVE="/data0/www/logs/archives"
# Nginx 的Pid 文件
PID="/apps/nginx/logs/nginx.pid"
# 删除 30天以前的日志
find $LOGARCHIVE -type f -atime +30 -exec rm -f {} \; > /dev/null 2>&1
# 删除空目录
find $LOGARCHIVE -type d -empty -exec rmdir {} \; >/dev/null 2>&1
# 获取前一天的时间
DATE=`date --date="LAST DAY" "+%y%m%d"`
# 创建前一天归档日志目录
LOGARCHIVE="$LOGARCHIVE/$DATE"
test -d $LOGARCHIVE || mkdir -p $LOGARCHIVE
cd $LOGDIR
for FILE in *$LOGSUFFIXA*; do
    mv $FILE $LOGARCHIVE
done
# 发送 USR1 信号给Nginx, 让Nginx 重新打开

yum方式安装方式自带的logrotate日志切割。

[root@test ~]# vim /etc/logrotate.d/nginx 
/var/log/nginx/*log {
    create 0664 nginx root
    daily
    rotate 10
    missingok
    notifempty
    compress
    sharedscripts
        /bin/kill -USR1 `cat /run/nginx.pid 2>/dev/null` 2>/dev/null || true
    endscript
}

6.5 Nginx压缩

Nginx支持对指定类型的文件进行压缩然后再传输给客户端,而且压缩还可以设置压缩比例压缩后的文件大小将比源文件显著变小,这样有助于降低出口带宽的利用率,降低企业的支出,不过会占用相应的CPU资源。 nginx对文件的压缩功能是依赖于模块ngx_http_gzip_module

范例:

#启用或禁用gzip压缩,默认关闭
gzip on|off;

#压缩比由低到高,从1-9,默认为1
gzip_comp_level level;

#禁用ie6 gzip功能
gzip_disable "MSIE [1-6]\.";

#gzip压缩的最小文件,小于设置值的文件将不会被压缩
gzip_min_length 1k;

#启用压缩功能时,协议的最小版本,默认HTTP/1.1
gzip_http_vsersion 1.0|1.1;

#指定Nginx服务需要向服务器申请的缓存空间的个数和大小,平台不通过,默认:32 4k或者16 8k
gzip_buffers number size;

#指明仅对哪些类型的资源执行压缩操作;默认为gzip_types test/html,不用显示指定,否则出错
gzip_types mime-type ...;

#如果启用压缩,是否在响应报文首部插入"Vary:Accept-Encoding",一般建议打开
gzip-vary on|off;

6.6 https

Web网站的登录页面都是使用 Webhttps, , HTTPS,加密传输的,加密数据以保障数据的安全,HTTS能够加密信息,以免敏感信息被第三方获取,所以很多银行网站或电子邮箱等等安全级别较高的服务都会采用 HTTPS, HTTPS HTTP+ SSL/ TLS, http协议,HTTPS实是有两部分组成:HTTP+SSL/TLS,也就是在HTTP上又加了一层处理加密信息的模块。服务端和客户端的信息传输都会通过TLS进行加密,所以传输的数据都是加密后的数据。

6.6.1 https配置参数

配置参数

ssl on|off;
listen 443 ssl;
#为指定的虚拟主机配置是否启用ssl功能,此功能在1.15.0废弃,使用listen[ssl]替代

ssl_certificate /path/to/file;
#指向包含当前虚拟主机和CA的两个证书信息的文件,一般是crt文件

ssl_certificate_key /path/to/file;
#当前虚拟主机使用的私钥文件,一般是key文件

ssl_protocols [SSLv2] [SSLv3] [TLSv1] [TLSv1. 1] [TLSv1.2];
#支持ssl协议版本,早期为ssl现在是TLS,默认为后三个

ssl_session_cache off | none | [builtin[:size]] [shared:name:size];
#配置ssl缓存
   off:#关闭缓存
   none: #通知客户端支持 ssl session cache,但实际不支持
   builtin[:size]: #使用openssL内建缓存,为每 worker进程私有
   [shared:name:size]: #在各worker之间使一个共享的缓存,需要定义一个缓存名称和缓存空间大小一兆可以存储4000个会话信息,多虚拟主机可以使用相同的缓存名称
ssl_session_timeout time;
#客户端连接可用复用ssl_session_cache中缓存的有效时长,默认5m
6.6.2 自签名证书生成
[root@localhost ~]# openssl genrsa -out cakey.pem 2048
# 生成根密钥
[root@localhost ~]# [root@localhost ~]# openssl req -new -x509 -key cakey.pem -out cacert.pem
# 生成根证书
[root@localhost ~]# openssl genrsa -out nginx.key 2048
# 生成server上的密钥
[root@localhost ~]# openssl req -new -key nginx.key -out nginx.csr
# 生成server上的证书
[root@localhost ~]# openssl x509 -req -in nginx.csr -CA cacert.pem -CAkey cakey.pem -CAcreateserial -out nginx.crt
# 使用私有根证书CA请求签发证书
6.6.3 范例
server {
    listen 80;
    server_name localhost;
    rewrite ^(.*)$  https://$host$1 permanent;
}
server {
    listen 443 ssl;
    root html;
    ssl_certificate /apps/nginx/conf/certs/nginx.crt;
    ssl_certificate_key /apps/nginx/conf/certs/nginx.key;
    ssl_session_cache    shared:SSL:1m;
    ssl_session_timeout  5m;
}

七、Nginx+PHP-FPM

7.1 PHP-FPM

​ PHP-FPM(FastCGI Process Manager:FastCGI进程管理器)是一个PHPFastCGI管理器。它提供了 更好的PHP进程管理方式,可以有效控制内存和进程、可以平滑重载PHP配置。在日常运维中,我们主 要将PHP-FPM 的配置文件分为主配置文件和 pool配置文件(每个pool配置文件通常对应一个Nginx虚拟 主机)。

7.2 PHP-FPM主配置文件

[root@localhost ~]# cat /etc/php-fpm.conf
[global]
pid = /var/run/php-fpm.pid
error_log = /var/log/php-fpm.log
process_control_timeout = 0

process.max = 2048
#动态方式下开启的php-fpm进程的最大数量

daemonize = yes
#设置 fpm 在后台运行

rlimit_files = 65535
#设置进程可以打开的文件描述符数量

rlimit_core = 67108864
#设置core dump 的大小

events.mechanism = epoll
#设置FPM 的事件处理机制

;emergency_restart_interval #所设值内出现SIGSEGV或者SIGBUS错误的php-cgi进程数如果超过emergency_restart_threshold个,php-fpm就会优雅重启

emergency_restart_threshold = 10
emergency_restart_interval = 5

include = /etc/fpm.d/*.conf
#加载pool池配置

7.3 PHP-FPM pool池配置

##配置文件目录:/etc/php-fpm.d/
[test.com]
user = www
group = www
listen = 127.0.0.1:9000

listen.allowed_clients = 127.0.0.1
#允许监听的客户端

pm = dynamic
#设置动态进程池

pm.max_children = 512
pm.start_servers = 32
pm.min_spare_servers = 32
pm.max_spare_servers = 64

pm.max_requests = 1500
#设置每个进程可处理的请求数,当进程达到这个请求数量后会自动释放在重新生成新的进程。避免内存泄漏等情况


pm.status_path = /test_monitor_page
#FPM 的监控设置

slowlog = /data0/www/logs/$pool-slow_log
#PHP-FPM 的慢请求日志位置。$pool 这里为 test.qfedu.com

request_slowlog_timeout = 3
#设置请求时间达到多少位慢请求

request_terminate_timeout = 20
#终止请求超时时间。一个请求若处理大于20s ,则会自动kill 掉。避免进程堆积

catch_workers_output = no

security.limit_extensions = ""
#限制 FPM 允许解析的脚本扩展名. 这里不限制,FPM可以解析任何扩展名的文件

7.4 Nginx结合PHP-FPM

7.4.1 PHP-FPM pool池配置
[test.com]
user = nginx
group = nginx
listen = 127.0.0.1:9000
listen.allowed_clients = 127.0.0.1
pm = dynamic
pm.max_children = 512
pm.start_servers = 32
pm.min_spare_servers = 32
pm.max_spare_servers = 64
pm.max_requests = 1500
pm.status_path = /test_monitor_page
slowlog = /data0/www/logs/$pool-slow_log
request_slowlog_timeout = 3
request_terminate_timeout = 20
catch_workers_output = no
security.limit_extensions = ""
7.4.2 Nginx虚拟主机配置
server {
    listen 80;
    server_name test.com;
    root /data0/www/htdocs/test.com;
    access_log /var/log/nginx/test.com-acess.log;
    error_log /var/log/nginx/test.com-error.log;
    location ~ .*\.(gif|jpg|jpeg|png|bmp|swf|html)$ {
        expires 1d; #配置缓存时间
    }
    location ~ \.php$ {
    # 确保 fastcgi.conf 中存在 SCRIPT_FILENAME 配置
    root html;
    # 使用了PHP-FPM 9000 端口的POOL 配置。
    fastcgi_pass 127.0.0.1:9000;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    fastcgi_index index.php;
    include fastcgi_params;
    }
}
7.4.3 测试
[root@localhost ~]# echo "<?php phpinfo(); ?>" >/apps/nginx/html/index.php

八、Nginx均衡负载

使用代理服务器可以将请求转发给内部的Web服务器,使用这种加速模式显然可以提升静态网页的访问速度。因此也可以考虑使用这种技术,让代理服务器将请求 均匀转发给多台内部Web服务器之一上,从而达到负载均衡的目的。这种代理方式与普通的代理方式有所不同,标准代理方式是客户使用代理访问多个外部Web 服务器,而这种代理方式是多个客户使用它访问内部Web服务器,因此也被称为反向代理模式。

8.1 Nginx反向代理

反向代理服务器位于用户与目标服务器之间,但是对于用户而言,反向代理服务器就相当于目标服务器,即用户直接访问反向代理服务器就可以获得目标服务器的资源。同时,用户不需要知道目标服务器的地址,也无须在用户端作任何设定。反向代理服务器通常可用来作为Web加速,即使用反向代理作为Web服务器的前置机来降低网络和服务器的负载,提高访问效率。

8.1.1 功能模块
Ngx_http_upstream_module ---upstream
8.1.2 模块配置
Syntax: proxy_pass URL; #代理的后端服务器URL或ip地址或upstream池

Syntax: proxy_buffering on | off; #代理缓存开关
#proxy_buffering开启的情况下,nignx会把后端返回的内容先放到缓冲区当中,然后再返回给客户端(边收边传,不是全部接收完再传给客户端)。

Default: proxy_buffer_size 4k|8k; #缓冲区大小


Syntax: proxy_buffers number size; #缓冲区数量

Syntax: proxy_busy_buffers_size size; #忙碌的缓冲区大小控制同时传递给客户端的buffer数量

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; # 链接超时

Syntax: proxy_read_timeout time;

Syntax: proxy_send_timeout time; #nginx进程向 fastcgi 进程发送request的整个过程的超时时间


# buffer 工作原理
1. 所有的 proxy buffer 参数是作用到每一个请求的。每一个请求会安按照参数的配置获得自己的
buffer。proxy buffer 不是 global而是per request的。
2. proxy_buffering 是为了开启代理服务器的响应缓冲,开启后 proxy_buffers 和
proxy_busy_buffers_size参数才会起作用。
3. 无论 proxy_buffering 是否开启,proxy_buffer_size(main buffer)都是工作的,
proxy_buffer_size所设置的buffer_size 的作用是用来存储 upstream 端response 的
header。
4. 在 proxy_buffering 开启的情况下,Nginx 将会尽可能的读取所有的 upstream 端传输的数据到
buffer,直到 proxy_buffers设置的所有buffer们被写满或者数据被读取完(EOF)。此时 nginx 开
始向客户端传输数据,会同时传输这一整串buffer,同时如果response的内容很大的话,Nginx会接收并
把他们写入到 temp_file里去。大小由proxy_max_temp_file_size 控制。如果busy的buffer传输
完了会从temp_file里面接着读数据,直到传输完毕。
5. 一旦proxy_buffers设置的buffer被写入,直到buffer里面的数据被完整的传输完(传输到客户
端),这个buffer将会一直处在busy状态,我们不能对这个buffer进行任何别的操作。所有处在busy状
态的buffer size加起来不能超过proxy_busy_buffers_size,所以proxy_busy_buffers_size是
用来控制同时传输到客户端的 buffer数量的。
8.1.3 反向代理配置
server {
    listen 80;
    server_name www.1000phone01.com;
    root /usr/share/nginx/html;
# Load configuration files for the default server block.
# include /etc/nginx/default.d/*.conf;
    location / {
        proxy_pass http://192.168.28.129:80;
        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_set_header X-Forwarded-Proto $scheme;
        proxy_set_header X-NginX-Proxy true;
        proxy_connect_timeout 30;
        proxy_send_timeout 60;
        proxy_read_timeout 60;
        proxy_buffering on;
        proxy_buffer_size 32k;
        proxy_buffers 4 128k;
        proxy_busy_buffers_size 256k;
        proxy_max_temp_file_size 256k;
    }

    location = /40x.html {
        error_page 404 /404.html;
    }
error_page 500 502 503 504 /50x.html;
    location = /50x.html {
        error_page 404 /404.html;
    }
}
8.1.4 反向代理扩展说明
  1. 后端web多域名反向代理需要设置反向代理协议头header。否则在访问另外一个域名时都会被代理到最先加载的域名
#方法:在每个server区域的反向代理location区域添加
proxy_set_header Host $host;
  1. 访问网站用户的地址信息无法统计,在代理后后端web接收的源ip地址为反向代理服务器,所以日志中无法统计用户来源ip
#方法:在每个server区域的反向代理location区域添加
proxy_set_header X-Forwarded-For $remote_addr;
  1. 访问负载均衡会出现错误页面,影响用户页面(Nginx的后端健康检查只是检查服务是否正常,如后端web服务的站点目录出现错误,有的用户访问将会访问到错误的页面)
#方法:在每个server区域的方向代理location区域添加
proxy_next_upstream error timeout http_404 http_502 http_403;
#如有其他错误页面可继续添加

8.2 Nginx均衡负载

8.2.1 功能模块
ngx_http_upstream_module
8.2.2 模块配置
upstream webapp {
    server 192.168.100.100:80;
    server 192.168.100.101:80;
}
8.2.3 均衡负载配置
upstream webapp {
    server 192.168.100.100:80;
    server 192.168.100.101:80;
}
server {
    root html;
    server_name www.webapp.com;
    location / {
        proxy_pass http://webapp;
    }
}
8.2.4 负载扩展说明
8.2.4.1 实现不同调度功能
1.  轮询(默认)
2.  权重分配 weight=x
3.  实现热备功能 backup (当所有服务器宕机时热备将启用)
4.  定义最大失败次数 当后端web尝试访问失败次数超过时踢出此后端web服务器
#max_fails=x
5.  定义失败之后重发的间隔时间 fail_timeout=x
8.2.4.2 实现不同调度算法
1.  rr轮询
2.  wrr权重
3.  ip_hash 每个请求按访问ip的hash分配,这样来自同一ip固定访问一台服务器
    #开启方法,在upstream语句块中添加一行ip_hash;
4.  least_conn 最小连接数,哪台后端服务器连接数最少就将请求发给哪台服务器
5.  url_hash 按照访问的rul的hash结果分配
#注:轮询只是简单实现请求的顺序转发,并没有考虑不同服务器的性能差异;
#加权轮询设置了初始时服务器的权重,但是没有考虑运行过程中的服务器状态;
#IP Hash保证同一个客户端请求转发到同一个后台服务器实现了session保存,然而当某一后台服务器发生故障时,某些客户端将访问失败;
#最少连接数只是考虑了后端服务器的连接数情况,并没有完全考虑服务器的整体性能。

8.3 均衡负载实验构建

8.3.1 准备三台服务器

一台作为nginx 均衡负载服务器,两台最为web服务器

Nginx服务器IP地址:192.168.100.100

Web1服务器IP地址:192.168.100.105

Web2服务器IP地址:192.168.100.101

8.3.2 配置web服务器

分别下载httpd服务器

Web1

[root@localhost yum.repos.d]# yum -y install httpd
[root@localhost yum.repos.d]# echo "nfs" >/var/www/html/index.html
[root@localhost yum.repos.d]# systemctl start httpd

Web2

[root@localhost yum.repos.d]# yum -y install httpd
[root@localhost yum.repos.d]# echo "backup" >/var/www/html/index.html
[root@localhost yum.repos.d]# systemctl start httpd

两台部署不同的web页面,在负载均衡时才能看出效果

8.3.3 Nginx均衡负载服务器安装nginx
[root@localhost yum.repos.d]# yum -y install nginx
[root@localhost yum.repos.d]# systemctl start nginx
8.3.4 Nginx配置文件编写
[root@localhost wordpress]# vim /etc/nginx/conf.d/www.conf
upstream typecho { ----------------------设置代理池和定义服务器组名
    server 192.168.100.105:80; --------要代理的服务器,可加weight=1设置权重轮询方式等
    server 192.168.100.101:80; --------要代理的服务器
}
server {
    listen 80;
    server_name www.mytypecho.com;
    location / {
        proxy_pass http://typecho; ---------添加选择的代理池
        root /usr/share/nginx/html/www/wordpress;
        index test.php index.php index.html;
    }
    location ~ .php$ {
        root /usr/share/nginx/html/www/wordpress;
        fastcgi_pass 127.0.0.1:9000;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }
}
8.3.5 启动服务
[root@localhost wordpress]# systemctl restart nginx
8.3.6 测试访问

第一次访问:

{width="3.99950021872266in" height="0.8748906386701663in"}

第二次访问:

{width="3.6453772965879265in" height="0.9373829833770778in"}

这样实现的均衡负载调度

九、Nginx保持会话

nginx会话保持主要有以下几种实现方式。

9.1 ip_hash

ip_hash 使用源地址哈希算法,将同一客户端的请求总是发往同一个后端服务器,除非该服务器不 可用。

ip_hash语法:

upstream myweb { 
    server 192.168.28.128:80; 
    server 192.168.28.135:80; 
} 
upstream myweb { 
    server 192.168.28.128:8080 weight=1; 
    server 192.168.28.135:8080 weight=2; 
} 
upstream myweb { 
    ip_hash; 
    server 192.168.28.128:80; 
    server 192.168.28.135:80; 
} 
upstream myweb { 
    server 192.168.62.157:8080 weight=2 max_fails=2 fail_timeout=2; 
    server 192.168.62.158:8080 weight=1 max_fails=2 fail_timeout=1; 
}

ip_hash 简单易用,但有如下问题 当后端服务器宕机后,session 会丢失; 不适用于前端还有代理的情况。必须是第一层代理,接受客户端的真实 ip 地址,二层代理无 法使用 来自同一局域网的客户端会被转发到同一个后端服务器,可能导致负载失衡; 不适用于 CDN 网络,

9.2 sticky_cookie_insert

使用 sticky_cookie_insert 启用会话亲缘关系,这会导致来自同一客户端的请求被传递到一组服务器的同一台服务器。与ip_hash不同之处在于,它不是基于IP来判断客户端的,而是基于cookie 来判 断。因此可以避免上述 ip_hash 中来自同一局域网的客户端和前端代理导致负载失衡的情况。

语法说明:

expires:#设置浏览器中保持 cookie 的时间 
domain:#定义cookie 的域 
path:#为cookie 定义路径 

9.3 jvm_route 方式

jvm_route是通过 session_cookie 这种方式来实现 session 粘性。将特定会话附属到特定 tomcat 上,从而解决 session 不同步问题,但是无法解决宕机后会话转移问题。如果在 cookie 和 url 中并没有 session,则这只是个简单的 round robin (轮巡) 负载均衡。 jvm_route的原理 一开始请求过来,没有带 session 的信息,jvm_route 就根据 round robin (轮巡)的方法, 发到一台 Tomcat 上面 Tomcat 添加上 session 信息,并返回给客户 用户再次请求,jvm_route 看到 session 中有后端服务器的名称,他就把请求转到对应的服务 器上 对于某个特定用户,当一直为他服务的 Tomcat 宕机后,默认情况下它会重试max_fails 的次 数,如果还是失败,就重新启用 round robin 的方式,而这种情况下就会导致用户的 session 丢失。

9.4 使用后端服务器自身通过相关机制保持 session 同步

如:使用数据库 redis、memcached 等做 session 复制

十、Nginx常用指令

10.1 if指令

10.1.1 if 判断

语法:

if (条件判断)
    {....}
#对给定的条件进行判断。如果为真,大括号的内容指令将被执行,当表达式只是一个变量时,如果值为空或任何以0开头的字符串都会当做false。if条件可以是如下任何内容:
规则 说明
=或!= 直接比较变量和内容
~ 区分大小写正则表达式匹配
~* 不区分大小写的正则表达式匹配
!~ 区分大小写的正则表达式不匹配
-f和!-f 用来判断文件是否存在
-d和!-d 用来判断目录是否存在
-e和!-e 用来判断文件或目录是否存在
-x和!-x 用来判断文件是否可执行
10.1.2 if判断可使用的全局变量
变量名称 变量说明
$args 这个变量等于请求行中的参数,同$query_string
$content_length 请求头中的Content-length字段
$content_type 请求头中的Content-Type字段
$document_root 当前请求在root指令中指定的值 $host 请求主机头字段,否则为服务器名称
$http_user_agent 客户端agent信息
$http_cookie 客户端cookie信息
$limit_rate 这个变量可以限制连接速率
$request_method 客户端请求的动作,通常为GET或POST
$remote_addr $remote_addr
$remote_port 客户端的端口
$remote_user 已经经过Auth Basic Module验证的用户名
$request_filename 当前请求的文件路径,由root或alias指令与URI请求生成
$scheme HTTP方法(如http,https)
$server_protocol 请求使用的协议,通常是HTTP/1.0或HTTP/1.1
$server_addr 服务器地址,在完成一次系统调用后可以确定这个值
$server_name 服务器名称
$server_port 请求到达服务器的端口号
$request_uri 包含请求参数的原始URI,不包含主机名,如:”/foo/bar.php?arg=baz”
$uri 不带请求参数的当前URI,$uri不包含主机名,如”/foo/bar.html”
$document_uri 与$uri相同例:
10.1.3 if语法实例
例1 :
# http://qf.com/ ==> http://jd.com
location /a {
    root /html;
    if ($host ~* qf.com ) {
        rewrite .* http://jd.com permanent;
    }
}
可以看到访问京东的页面

例2:
# http://qf.com/a/1.html ==> http://jd.com/a/1.html
location /a {
    root /html;
    if ($host ~* qf.com ){
        rewrite .* http://jd.com$request_uri permanent;
    }
}
访问页面会跳转到jd.com/a/1.html

例3 : 在访问目录后添加/ (如果目录后已有/,则不加/)
[root@nginx-server c]# pwd
/html/a/b/c
# http://qf.com/a/b/c
# $1: /a/b/
# $2: c
# http://$host$1$2/
location /a/b/c {
    root /html;
    index index.html index.hml;
    if (-d $request_filename) {
        rewrite ^(.*)([^/])$ http://$host$1$2/ permanent;
    }
}

10.2 set指令

与上面的自定义变量一致

10.3 return指令

return 指令用于返回状态码给客户端

10.3.1 语法
Syntax:   return code [text]
          return code URL;
          return URL;
Default:  —
Context:  server, location, if       
10.3.2 实例说明
例1 :如果访问的.sh结尾的文件则返回403操作拒绝错误
location ~* \.sh$ {
    return 403;
}
例2:80 ======> 443:80转443端口
# openssl genrsa -des3 -out server.key 2048
# openssl req -new -key server.key -out server.csr
# cp server.key server.key.org
# openssl rsa -in server.key.org -out server.key
# openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt
server {
    listen 80;
    server_name qf.com;
    access_log /var/log/nginx/http_access.log main;
    return 301 https://qf.com$request_uri;
}
server {
    listen 443 ssl;
    server_name qf.com;
    access_log /var/log/nginx/https_access.log main;
    ssl on;
    ssl_certificate /root/server.crt;
    ssl_certificate_key /root/server.key ;
    location / {
        root /html;
        index index.html index.htm;
    }
}
#浏览器访问测试

10.4 break 指令

10.4.1 语法

该指令用于"中断" 相同作用域下的所有 ngx_http_rewrite_module 模块中的指令。这个指令前的所 有rewrite 指令将会被执行,而之后的所有 rewrite 指令将被忽略。 该指令在server块、location 块及if块中使用。

Syntax:	break;
Default:	—
Context:	server, location, if
10.4.2 实例说明
locaton / {
    if($slow) {
        set $id "aa"; # 处于break指令之前,处于有效状态
        break;
        set $id2 "bb"; # 处于break指令之后,是一个无效指令
    }
}

注意: last 标记在本条 rewrite 规则执行完后,会对其所在的 server { … } 标签重新发起请求; break 标记则在本条规则匹配完成后,停止匹配,不再做后续的匹配;

十一、Nginx动态添加模块

在实际企业中如果Nginx已经编译安装好,想使用第三方插件或添加模块

首先查看Nginx版本和Nginx已安装的模块

[root@localhost conf.d]# nginx -v --------------#查看版本
nginx version: nginx/1.19.6
[root@localhost conf.d]# nginx -V ------------------查看已安装的模块
nginx version: nginx/1.19.6
built by gcc 4.8.5 20150623 (Red Hat 4.8.5-39) (GCC)
built with OpenSSL 1.0.2k-fips 26 Jan 2017
TLS SNI support enabled
configure arguments: --prefix=/etc/nginx --sbin-path=/usr/sbin/nginx

11. 1 安装git

[root@localhost tmp]# yum -y install git

11. 2 下载模块

[root@localhost tmp]# git clone <https://github.com/cuber/ngx_http_google_filter_module.git>

11. 3 添加模块

[root@localhost nginx-1.19.4]# ./configure --prefix=/usr/local/nginx --user=nginx --group=nginx --with-http_ssl_module --with-http_image_filter_module --with-http_gzip_static_module --with-http_auth_request_module --with-http_stub_status_module --with-http_perl_module --with-google_perftools_module --with-pcre --add-module=/tmp/ngx_http_google_filter_module/

在最后添加---add-module指定要添加的模块位置

11. 4 Make

不要执行最后的make install 否则会将原nginx覆盖

到原Nginx目录的sbin目录下,将原Nginx文件备份,然后将/tmp/ nginx-1.19.4/objs/下的Nginx移动到原nginx/sbin目录下

11. 5 启动

在启动nginx时可能会报错日志文件没有,对其进行创建即可

还可能显示perl库无法加载。解决方法:

[root@localhost ~]# mkdir -p /usr/local/lib64/perl5/auto/nginx
[root@localhost nginx-1.19.4] cp -a 
objs/src/http/modules/perl/blib/arch/auto/nginx/nginx.bs
objs/src/http/modules/perl/blib/arch/auto/nginx/nginx.so
/usr/local/lib64/perl5/auto/nginx
[root@localhost nginx-1.19.4] cp -a 
objs/src/http/modules/perl/blib/lib/nginx.pm
/usr/local/lib64/perl5/

十二、Nginx升级

12.1 版本升级

当我们使用的Nginx 版本存在BUG,亦或希望使用更高级的功能时。就有可能需要对我们目前使用 的Nginx 版本进行升级。那如何升级呢? 我们这里分为理想情况的升级,和实际工作中的升级去分析。

12.1 理想情况的版本升级

有可能你真的没有什么运维经验,将实际情况想象的过于复杂。网上看到的一切有关平滑升级的情 况没有问题,但基本上都是针对单点Nginx 去做的升级。而实际运维工作中,我们不可能让单点Nginx 服务存在。如果逼不得已真的存在,请按照下面的升级方案升级吧。

12.1.1 版本升级步骤
# 检查当前Nginx 版本
[root@test.com ~]# /usr/local/nginx/sbin/nginx -V
# 确保当前版本的nginx 是存活的
[root@test.com ~]# ps -ef |grep nginx
# 编译安装高版本Nginx
[root@test.com ~]# wget http://nginx.org/download/nginx-1.9.9.tar.gz
[root@test.com ~]# tar xf nginx-1.9.6.tar.gz
[root@test.com ~]# cd nginx-1.9.6
[root@test.com nginx-1.9.6]# ./configure --prefix=/usr/local/nginx/
[root@test.com nginx-1.9.6]# make
# 备份旧的nginx,一方面是等一下需要把新的nginx复制过来,另一方面的如果新的nginx有问题还可以
进行恢复
[root@test.com mv /usr/local/nginx/sbin/nginx{,.bak}
#把编译好的新的nginx文件服务到指定的安装目录中
[root@test.com nginx-1.9.6]# cp objs/nginx /usr/local/nginx/sbin/
# 检查高版本Nginx 对原有配置文件是否兼容
[root@test.com sbin]# /usr/local/nginx/sbin/nginx -t
#使用新版本的Nginx文件启动服务,之后平缓停止原有Nginx进程
[root@test.com nginx-1.9.6]# kill -USR2 `cat /nginx/logs/nginx.pid`
# 可以看到这里自动把之前的nginx.pid命名为nginx.pid.oldbin,并为新的nginx生成nginx.pid
[root@test.com nginx-1.9.6]# cd /nginx/logs/
nginx.pid nginx.pid.oldbin
#平缓停止旧服务的worker process
[root@test.com logs]# kill -WINCH `cat /nginx/logs/nginx.pid.oldbin`
# 检查是否升级成功
[root@test.com logs]# /usr/local/nginx/sbin/nginx -V
# 检查Nginx 进程是否存在
[root@test.com logs]# ps -aux |grep nginx
12.2 实际工作中的版本升级

​ 在实际工作中,Nginx 服务不可能单点部署。我们往往面临的是一个Nginx 服务集群。再按照理想 的情况进行升级,就有些得不偿失了。 那如何操作才能保证整个Nginx服务集群都升级OK呢? 可想而知,服务器集群的前端必有反向代理,反向代理对整个服务器集群是有健康检查的。如果健康检 查发现了某台服务器已经DOWN机,就会将机器从反向代理中摘除。这样就不会有生产环境的流量引 入。当健康检查检测到服务器UP后,会再将这台服务器添加到反向代理上,这之后生产流量才会引 入。 因此在实际工作场景中,我们只需要关闭Nginx 服务、升级Nginx 软件包、启动Nginx服务即可。

12.2.1 版本升级步骤
1) 关闭 Nginx 服务 /usr/local/nginx/sbin/nginx -s stop 或者 kill QUIT PID
2)升级 Nginx 二进制文件
3) 启动Nginx 服务 /usr/local/nginx/sbin/nginx
# 注意,请将Nginx 的路径替换成真是的路径

12.2 热部署

假设nginx正在提供服务,一切正常,现在我们想要对nginx进行热升级,大致步骤如下

0、最重要的一步,备份。备份老的nginx文件
cp -r /apps/nginx/ /tmp/nginx-back

1、下载新版本的nginx,根据老版本的编译选项,对新版本完成编译的步骤,只对新版本进行编译操作,不执行安装操作,换句话说就是,只执行make命令,不执行make install命令,完成编译操作后,即可获取到我们需要的新版本的二进制文件,之后,我们需要根据实际情况判断哪些文件需要被替换,此处描述的”根据情况判断”在后文中会有解释,先不用纠结,此处假设,根据情况判断后,只需要替换nginx二进制文件。

2、确定已经备份老版本的nginx二进制文件,以防万一,用编译好的新版本的nginx二进制文件替换老版本的nginx二进制文件,此时老版本的nginx仍然在内存中正常运行,所以不用担心,我们替换的只是硬盘中的二进制文件,做好备份即可。

3、对nginx的master进程(正在运行的老版本的master进程)发送USR2信号,老版本的master进程收到信号后,会通过新版本的二进制文件启动新版本的master进程,新版本的master进程会启动新版本的worker进程,此时新老版本的nginx进程同时存在。
kill -USR2 58893
[root@test ~]# ps -ef |grep nginx
root      58893      1  0 19:20 ?        00:00:00 nginx: master process /apps/nginx/sbin/nginx
nobody    58894  58893  0 19:20 ?        00:00:00 nginx: worker process
nobody    80857  58893  0 19:28 ?        00:00:00 nginx: worker process
root      84420  58893  0 19:30 ?        00:00:00 nginx: master process /apps/nginx/sbin/nginx
nobody    84421  84420  0 19:30 ?        00:00:00 nginx: worker process
nobody    84422  84420  0 19:30 ?        00:00:00 nginx: worker process
root      84484  76013  0 19:30 pts/2    00:00:00 grep --color=auto nginx


4、向老版本的master进程发送WINCH信号,以便先优雅的停止老版本的worker进程,新的请求会被新版本的worker进程处理,此时老的master进程仍然存在,留下老的master进程是为了以防万一,以便随时回滚,此时老版本的master进程、新版本的master进程和新版本的worker进程同时存在(确定升级完毕可将老的master杀死),升级过程暂且完毕。
kill -WINCH 58893
[root@test ~]# ps -ef |grep nginx
root      58893      1  0 19:20 ?        00:00:00 nginx: master process /apps/nginx/sbin/nginx
root      84420  58893  0 19:30 ?        00:00:00 nginx: master process /apps/nginx/sbin/nginx
nobody    84421  84420  0 19:30 ?        00:00:00 nginx: worker process
nobody    84422  84420  0 19:30 ?        00:00:00 nginx: worker process
root      87173  76013  0 19:31 pts/2    00:00:00 grep --color=auto nginx


5、如果升级后万一出现问题,则可以随时进行回滚,由于老版本的master进程并未停止,所以我们可以向老的master进程发送HUP信号,即可通过老版本的master进程重新生成老版本的worker进程,当老版本的worker进程重新被拉起后,即可向新版本的master进程发送QUIT信号,以便优雅的关闭新版本的nginx进程,回滚操作完毕。
kill -HUP 58893
kill -QUIT 77202

十三、nginx配置优化(配合十六进行优化)

13.1 worker_processes优化

worker_processes 1;

一般将此值设置为与CPU核心数相同即可。

13.2 worker_cpu_affinity优化

worker进程是工作在CPU核心上。在默认配置下,worker进程会不固定的工作在某个核心上,在切换核心时会造成worker进程重新读取一些缓存。所以可以设置worker进程绑定在某个CPU核心上。

worker_cpu_affinity 0001 0010 0100 1000

此为4核心下,1的位置为绑定在第几个核心上。此配置要配置在全局配置。局部不行。

13.3 worker_priority优化

此值可设置worker进程在系统中nice的优先级,官方写的范围为-20到20,实际测试只有-20到19。值越小其优先级越大。

worker_priority 0;

13.4 worker_rlimit_nofile优化

设置worker进程能够打开的最大文件数量。相当于最大连接数。虽然设置了此值,但是如果linux系统的FD(文件描述符)的最大值没设置的话也无法生效。所以此值需配合linux系统的FD数量。

worker_rlimit_nofile 65536;

linux系统设置FD数量方法,使用命令的方式是临时修改。永久需修改内核参数。

[root@localhost ~]# ulimit -n 65535
[root@localhost ~]# vim /etc/security/limits.conf 
*                soft    nofile          65535
*                hard    nofile          65535

在末行添加以上内容,重启生效。

其他ulimit优化

*                soft    core          unlimited
*                hard    core          unlimited
*                soft    nproc         1000000
*                hard    nproc         1000000
*                soft    memlock       32000
*                hard    memlock       32000
*                soft    msgqueue      8192000
*                hard    msgqueue      8192000

worker_rlimit_nofile的优化还需配合events语句块中的worker_connections 10240;将此值调大。

13.5 worker_connections优化

worker_connections 10240;

设置单个进程的最大并发连接数,此值设置最好worker_connections*CPU核心数等于worker_rlimit_nofile

13.6 accept_mutex优化

accept_mutex on;

当为on时,在一个新的请求过来时,如有4个worker在休眠,就只会唤醒一个worker进行处理,每个新的请求过来时单独唤醒一个进行处理。为off时,当有一个新的请求过来时,将会唤醒所有的worker进程,然后worker进程之间竞争处理新的请求。建议此值设置为on。

13.7 multi_accept优化

multi_accept off;

为on时nginx服务器的每个工作进程可以同时接受多个新的网络连接。为off时一个工作进程只能接受一个新的网络连接。建议设置为on。

十四、Nginx均衡负载企业应用

14.1 (动静分离架构)根据用户访问的uri进行均衡负载

注:可能出现的错误,所有配置完成后nginx配置文件没错。但是访问某个集群时(如访问www.test.com/upload )出现404,则为后端集群配置没有对应目录,nginx在反向代理时的请求url会是http://upload/upload最后一个upload必须是在集群节点站点根目录下的upload。否则代理请求为http://192.168.100.101/upload而后端节点为http://192.168.100.101造成在后端节点上找不到upload目录。

(1)三个后端集群 /upload 集群-192.168.100.101 用户上传集群

​ /static 集群-192.168.100.102 用户静态页面集群

​ / 集群-192.168.100.105 用户默认访问页面集群

(2)三个集群分别部署不同站点页面 192.168.100.105

[root@localhost html]# echo "defaults-web 192.168.100.105" >/usr/share/nginx/htmldefault/index.html

192.168.100.102

[root@localhost html]# echo "static-web 192.168.100.102" >/usr/share/nginx/html/static/index.html

192.168.100.101

[root@localhost html]# echo "upload-web 192.168.100.101" >/usr/share/nginx/html/upload/index.html
  1. 配置lb均衡负载
upstream upload {
    server 192.168.100.101:80;
}
upstream default {
    server 192.168.100.105:80;
}
upstream static {
    server 192.168.100.102:80;
}
server {
    listen 80;
    server_name www.test.com;
    location / {
        proxy_pass http://default;
        proxy_set_header Host $host; #此为在反向代理是设置反向代理的头部信息添加主机名信息
        proxy_set_header X-Forwarded-For $remote_addr;  #此为在反向代理是设置反向代理的头部信息添加访问请求的客户端ip地址(公网IP)
        proxy_next_upstream error timeout http_404 http_502 http_403;
    }
    location /static {
        proxy_pass http://static;
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-For $remote_addr;
        proxy_next_upstream error timeout http_404 http_502 http_403;
    }
    location /upload {
        proxy_pass http://upload;
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-For $remote_addr;
        proxy_next_upstream error timeout http_404 http_502 http_403;
    }
}

Nginx的静态处理能力很强,但是动态处理能力不足,因此,在企业中常用动静分离技术。动静分离技术其实是采用代理的方式,在server{}段中加入带正则匹配的location来指定匹配项针对PHP的动静分离:静态页面交给Nginx处理,动态页面交给PHP-FPM模块或Apache处理。在Nginx的配置中,是通过location配置段配合正则匹配实现静态与动态页面的不同处理方式。

总结:

  1. 提高网站服务安全性

  2. 管理操作工作简化

  3. 可以换分不同人员管理不同集群服务器

14.2 根据用户的user-agent信息均衡负载

根据用户的请求终端对用户显示对应终端的页面

  1. 三个集群
Android     -192.168.100.101
Pc          -192.168.100.102
Default     -192.168.100.105

(2)三个分别部署不同页面 192.168.100.101

[root@localhost html]# echo "Android-web 192.168.100.101" >/usr/share/nginx/html/android/index.html

192.168.100.105

[root@localhost html]# echo "PC-web 192.168.100.105" >/usr/share/nginx/html/pc/index.html

192.168.100.102

[root@localhost html]# echo "default-web 192.168.100.102" >/usr/share/nginx/html/default/index.html

(3)配置Nginx配置文件

upstream android {
    server 192.168.100.101:80;
}
upstream pc {
    server 192.168.100.105:80;
}
upstream default {
    server 192.168.100.102:80;
}
server {
    listen 80;
    server_name www.test1.com;
    location / {
        if ($http_user_agent ~* windows){
            proxy_pass http://pc;
        }
        if ($http_user_agent ~* android){
            proxy_pass http://android;
        }
        proxy_pass http://default;
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-For $remote_addr;
        proxy_next_upstream error timeout http_404 http_502 http_403;
    }
}

十五、企业中均衡负载部署

先部署一台LNMP服务器,上传代码信息

进行访问测试

批量部署多台web服务器

将nginx配置文件进行分发

将站点目录分发给所有主机

相关笔记

2 分钟阅读698 字

LNMP

Yum安装LNMP环境 一、安装Nginx 配置Nginx官方repo源 安装Nginx 启动nginx,启动后访问IP:80端口即可 二、安装MySQL 2.1 配置MySQL repo源 默认开启的为8.0版本,可关闭8.0,开启别的

继续阅读
6 分钟阅读1,922 字

haproxy

Haproxy 一、 Haproxy概述 (1) HAProxy 是一款提供高可用性、负载均衡以及基于TCP(第四层)和HTTP(第七层)应用的代理软件,支持虚拟主机,它是免费、快速并且可靠的一种解决方案。 HAProxy特别适用于那些负载

继续阅读
8 分钟阅读2,655 字

lvs

LVS LVS(Linux Virtual Server)即Linux虚拟服务器,是由章文嵩博士主导的开源负载均衡项目,目前LVS已经被集成到Linux内核模块中。该项目在Linux内核中实现了基于IP的数据请求负载均衡调度方案,其体系结构

继续阅读