Nginx安装

安装方式一:rpm的Nginx(了解)

安装步骤:

  1. 建立yum源

    1
    yum install epel-release -y
  2. 查看nginx源

    1
    yum list all | grep nginx
  3. 安装nginx

    1
    yum install nginx -y
  4. 查看已安装的nginx,列出安装nginx相关目录

    1
    rpm -ql nginx
  5. 启动nginx

    1
    2
    3
    4
    5
    6
    7
    8
    # 查看nginx启动目录
    rpm -ql nginx | grep bin
    # 查看帮助文档
    /usr/sbin/nginx -h
    # 启动
    /usr/sbin/nginx
    # 查看端口号
    netstat -tnlp | grep :80
  6. nginx启动后,查看进程

    1
    ps -ef | grep nginx

    注:会启动两个进程master和worker

  7. 查看nginx log

    1
    cd /var/log/nginx

安装方式二:tar.gz的Nginx

Nginx的安装方式有多种,本次安装是用tar.gz,在Linux(CentOS7)环境下安装,由于在安装Nginx的时候,需要提前安装依赖,因此我们全部写到Shell脚本中,不在单独命令行安装,Shell脚本如下:

1
2
3
4
5
6
7
8
9
10
[root@localhost ~]# cat nginx_install.sh
#!/bin/bash
yum install -y pcre-devel openssl-devel gcc curl
wget http://nginx.org/download/nginx-1.18.0.tar.gz
tar -zxvf nginx-1.18.0.tar.gz
mv nginx-1.18.0/ /usr/local/nginx/
cd /usr/local/nginx/
./configure --prefix=/usr/local/nginx --conf-path=/usr/local/nginx/nginx.conf
cd /usr/local/nginx/
make && make install

直接运行

1
[root@localhost ~]# sh nginx_install.sh

安装完成,启动Nginx

1
2
[root@localhost ~]# cd /usr/local/
[root@localhost local]# ./nginx/sbin/nginx

访问页面,查看结果

image-20210329211629096

Nginx命令

  • 查看帮助:nginx -?/-h

    • nginx -v:显示版本信息
    • nginx -V:显示版本和配置项信息
    • nginx -t:测试配置文件是否存在语法问题
    • nginx -T:检测配置文件是否有语法错误,转储并退出
    • nginx -q:检测配置期间屏蔽非错误信息,只输出错误信息
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    [root@localhost ~]# /usr/local/nginx/sbin/nginx -h
    nginx version: nginx/1.18.0
    Usage: nginx [-?hvVtTq] [-s signal] [-c filename] [-p prefix] [-g directives]

    Options:
    -?,-h : this help
    -v : show version and exit
    -V : show version and configure options then exit
    -t : test configuration and exit
    -T : test configuration, dump it and exit
    -q : suppress non-error messages during configuration testing
    -s signal : send signal to a master process: stop, quit, reopen, reload
    -p prefix : set prefix path (default: /usr/local/nginx/)
    -c filename : set configuration file (default: /usr/local/nginx/nginx.conf)
    -g directives : set global directives out of configuration file
    [root@localhost ~]# /usr/local/nginx/sbin/nginx -v
    nginx version: nginx/1.18.0
    [root@localhost ~]# /usr/local/nginx/sbin/nginx -t
    nginx: the configuration file /usr/local/nginx/nginx.conf syntax is ok
    nginx: configuration file /usr/local/nginx/nginx.conf test is successful
  • nginx -s

    • nginx -s reopen:重新打开日志文件
    • nginx -s stop:快速停止Nginx,此方法是先查看nginx主进程号,然后使用kill强制杀掉
    • nginx -s quit:优雅退出Nginx(推荐使用,此方法会等待Nginx进程处理完毕在停止)
    • nginx -s reload:重新加载配置并且启动
  • nginx [-c filename]:在启动Nginx时配置制定的配置文件

  • nginx -p:用于设置Nginx的前缀路径

  • nginx -g:在配置文件之外的设置全局命令

Nginx默认配置文件

目录:/nginx/nginx.cnf

Nginx配置文件主要分为六大区域:核心区域

  • main(全局设置):作用域是全局
  • events(nginx工作模式)
  • http(http设置)
    • upstream(负载均衡服务器设置,配置文件默认没有,需要手动添加)
    • server(主机设置)
    • location(URL配置)

image-20210329212020551

全局区域配置文件介绍

1
2
3
4
5
6
7
8
9
#user  nobody;
# nginx进程,一般数值为cpu核数
worker_processes 1;
# 错误日志存放目录
#error_log logs/error.log;
#error_log logs/error.log notice;
#error_log logs/error.log info;
# 进程pid存放位置
#pid logs/nginx.pid;

user:指定Nginx Worker进程运行用户以及用户组,默认由nobody账号运行,也可以创建nginx用户指定用户。

​ 例如:创建www用户,在nginx配置文件中将user nobody; 修改为 user www;即可,接下来进行如下步骤

​ /usr/sbin/groupadd www

​ /usr/sbin/useradd -g www www

worker_processes:指定Nginx要开启的子进程。每个Nginx进程平均耗费10M~12M内存。根据经验,一般1个进程就足够了,如果是多核CPU,建议指定和CPU的数量一样的进程数即可。这里写2的话,那么就会开启2个子进程,总共3个子进程。

error_log:用来定义全局错误日志文件。日志输出级别有debug、info、notic、warn、error、crit可供选,其中debug输出日志最为想写,而crit输出日志最少。

pid:用来指定进程id的存储文件位置。

(worker_rlimit_nofile:用于指定一个nginx进程可以打开最多文件描述数目,这里是65535,需要使用命令ulimit -n 65535来设置,配置文件默认没有)

event区域配置文件介绍

1
2
3
4
5
# 工作模式及连接数上限
events {
# 单个后台worker process进程的最大并发链接数
worker_connections 1024;
}

use:用来指定Nginx的工作模式。Nginx支持工作模式有select、poll、kqueue、epoll、rtsig和/dev/poll

​ 其中select和poll都是标准的工作模式,kqueue和epoll是高效的工作模式,不同的是epoll用在Linux平台上,而kqueue用在BSD系统中,对于Linux系统,epoll工作模式是首选。

​ 默认无该项,需手动添加:use epoll;

worker_connections:用于定义Nginx每个进程的最大连接数,即接受前端的最大请求数,默认是1024。最大客户端连接数由worker_processes和worker_connections决定,即mac_clients=worker_processesworker_connections,在作为反向代理时,max_clients变为:mac_clients=worker_processesworker_connections/4。进程的最大连接数受Linux系统进程的最大打开文件数限制,在执行操作系统命令ulimit -n 65535后worker_connections的设置才能生效。

HTTP区域配置文件介绍

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
http {
# 文件扩展名与类型映射表
include 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"';
# nginx访问日志
#access_log logs/access.log main;
# 开启高效传输模式
sendfile on;
# 激活tcp_nopush参数可以允许把httpresponse header和文件的开始放在一个文件里发布, 积极的作用是减少网络报文段的数量
#tcp_nopush on;
# 连接超时时间,单位是秒
#keepalive_timeout 0;
keepalive_timeout 65;
# 开启gzip压缩功能
#gzip on;

# 基于域名的虚拟主机
server {
# 监听端口
listen 80;
server_name localhost;
# 编码识别
#charset koi8-r;
# 日志格式及日志存放路径
#access_log logs/host.access.log main;

location / {
# 站点根目录,即网站程序存放目录
root html;
# 首页排序
index index.html index.htm;
}
# 错误页面
#error_page 404 /404.html;
# 将服务器错误页面重定向到静态页面/50x.html
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}


# 代理PHP脚本到Apache上监听127.0.0.1:80
#location ~ \.php$ {
# proxy_pass http://127.0.0.1;
#}


# 将PHP脚本传递到正在监听127.0.0.1:9000的FastCGI服务器
#location ~ \.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;
#}

# 如果Apache的文档根目录与nginx的根目录一致,则拒绝访问.htaccess文件
#location ~ /\.ht {
# deny all;
#}
}



# 另一个虚拟主机,混合使用IP、名称和基于端口的配置
#server {
# listen 8000;
# listen somename:8080;
# server_name somename alias another.alias;
# location / {
# root html;
# index index.html index.htm;
# }
#}


# HTTPS server
#
#server {
# listen 443 ssl;
# server_name localhost;
# 服务的证书
# ssl_certificate cert.pem;
# 服务端key
# ssl_certificate_key cert.key;
# 会话缓存
# ssl_session_cache shared:SSL:1m;
# 会话超时时间
# ssl_session_timeout 5m;
# #加密算法
# ssl_ciphers HIGH:!aNULL:!MD5;
# 启动加密算法
# ssl_prefer_server_ciphers on;

# location / {
# root html;
# index index.html index.htm;
# }
#}
}

http模块负责HTTP服务器相关属性的配置,有server和upstream两个子模块。

include:用来设定文件的mime类型,类型的在配置文件目录下的mimi.type(cat nginx/conf/mime.types)文件定义,告诉nginx识别文件类型

default_type:设定了默认的类型为二进制流,也就是当文件类型为定义时使用这种方式,例如在没有配置asp的locate环境时,Nginx是不予解析的,此时,用个浏览器访问asp文件就会出现下载。

log_format:用于设置日志的格式,和记录哪些参数,这里设置为main,刚好用于access_log来记录这种类型。

Nginx使用中的配置文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
#user  nobody;
worker_processes 2;
error_log logs/error.log;
pid logs/nginx.pid;

# 最大文件打开数(连接),可设置为系统优化后的ulimit -HSn的结果
worker_rlimit_nofile 360000;

events {
# epoll是多路复用IO(I/O Multiplexing)中的一种方式,但是仅用于linux2.6以上内核,可以大大提高nginx的性能
use epoll;
# 单个后台worker process进程的最大并发链接数
worker_connections 100000;
# 是否串行处理连接
multi_accept off;
}

http {
# 文件扩展名与类型映射表
include mime.types;
# 默认文件类型
default_type application/octet-stream;
# 设定请求缓存
# 户端请求的最大可接受体大小,由行表示
client_max_body_size 50m;
# 服务器名字的hash表大小
server_names_hash_bucket_size 256;
# 客户机的请求头设置大小,对于绝大多数请求,1K的缓冲区大小就足够了
client_header_buffer_size 256k;
# 用来指定客户端请求中较大的消息头的缓存最大数量和大小
large_client_header_buffers 4 256k;

# 用于配置转发至tomcat后;tomcat获取客户端正式ip
# 允许重新定义和添加一些将被传输到代理服务器的请求头行。作为值,可以使用文本、变量及其组合。
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Real-Port $remote_port;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

# 解决js跨域的问题
# 增加头标
add_header Access-Control-Allow-Origin *;
add_header Access-Control-Allow-Headers X-Requested-With;
add_header Access-Control-Allow-Methods GET,POST,OPTIONS;

# 指定客户机请求体缓冲区大小。
client_body_buffer_size 256k;
# 客户机的请求头设置读取超时。
client_header_timeout 3m;
# 客户机的请求体设置读取超时。
client_body_timeout 3m;
# 客户端分配响应超时时间。
send_timeout 3m;
# 访问日志存放路径
access_log no;
# 客户端连接保持活动的超时时间,在超过这个时间之后服务器会关闭该链接。
keepalive_timeout 0;
#修改或隐藏Nginx的版本号
server_tokens off;
#虚拟主机配置
server {
#listen指令指定所包含的服务器接受的地址和端口。可以只指定地址、端口或服务器名作为地址
listen 80;
#e用来指定ip地址或者域名,多个域名之间用空格分开
server_name localhost;
#对 "/gzh" 启用反向代理
location /gzh
{
#根据表达式来更改URI,或者修改字符串。注意重写表达式只对相对路径有效。
#此处是将/gzh以前的地址替换成http://weixin.qq.com/q/xxx
rewrite ^ http://weixin.qq.com/q/xxx;
}

location /test {
default_type text/html;
return 200 "207_80";
}

location / {
default_type text/html;
# 根据规则的执行情况,返回一个状态值给客户端。
return 200 "207_80";
}
location /status
{
# 这个模块能够获取Nginx自上次启动以来的工作状态,此模块非核心模块,需要在编译的时候手动添加编译参数
stub_status on;
# 日志
access_log /usr/local/nginx/logs/status.log;
}
location /lua{
default_type text/html;
content_by_lua_file /usr/local/op/code/test.lua;
}
location /comm{
default_type text/html;
if ( $request_uri ~* /comm/gzhqr ) {
content_by_lua_file /usr/local/op/code/redisget.lua;
}
proxy_pass http://192.168.1.209;
}

error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}

server
{
listen 192.168.88.100:8081;
server_name www.cs.cc;
default_type 'text/html';
charset utf-8;
# 日志级别
error_log logs/error.log info;
location /test {
default_type text/html;
return 200 "207_8081";
}
location /luac
{
default_type text/html;
#lua_code_cache off;
#$request_uri就是完整url中刨去最前面$host剩下的部分,比如http://www.baidu.com/pan/beta/test1?fid=3的就是/pan/beta/test1?fid=3
#~* /devc/gzhqr表示含有/devc/gzhqr为true
if ( $request_uri ~* /devc/test ) {
content_by_lua_file /usr/local/op/lualib/tcode/test1.lua;
}
}
location / {
root html;
index index8081.html index8081.htm;
}
}


server {
listen 8085;
listen 443 ssl;
# 填写绑定证书的域名
server_name www.cs.cc;
# 为服务器启用HTTPS。
#ssl on;
ssl_certificate /usr/local/op/nginx/conf/1_www.cs.cc_bundle.crt;
ssl_certificate_key /usr/local/op/nginx/conf/2_www.cs.cc.key;
ssl_session_timeout 5m;
# 指令启用所指示的协议。
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
# 描述了允许的密码。密码以OpenSSL支持的格式分配
ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:HIGH:!aNULL:!MD5:!RC4:!DHE;
# 要求协议SSLv3和TLSv1服务器密码优先于客户机的密码。
ssl_prefer_server_ciphers on;
charset utf-8;
resolver 114.114.114.114;
# 日志级别
error_log logs/error.log info;

# 网页
location ~/social_security_homepage.html {
rewrite ^(.*)$ /socialstop.html break;
}
# 网络资源路径
location /h5/huo/images/
{
proxy_pass http://192.168.1.209:3000/images/;
}
# 地址
location /h5/
{
proxy_pass http://192.168.1.209:3000/;
}

# 本地路径
location /upload/file/
{
root /opt/nci/NCI_DOWN/;
}
if ($request_uri ~* /wxapp/sign/)
{
rewrite ^/(.*) http://weixin.qq.com/r/xxx? permanent;
}

# 老管理平台图片的重写
if ($request_uri ~* /download/downLoad.do\?loadFile=/ITCT_Mng/image)
{
rewrite ^/(.*) https://www.cs.cc/upload/file$argloadFile? permanent;
}



# 管理平台的资源转发
if ($request_uri ~* ^(/PRO_GLPT/))
{
rewrite ^/PRO_GLPT/(.*)$ /glpt/$1 last;
# 没有匹配上返回403 状态码为444(此状态码是非标准的),那么直接关闭此TCP连接
#return code
#return code text 因为要带响应内容,因此code不能是具有跳转功能的30x
#return code URL 此时URI可以为URI做内部跳转,也可以是具有“http://”或者“https://”等协议的绝对URL,直接返回客户端,而code是30x(301, 302, 303, 307,308)
#return URL 此时code默认为302,而URL必须是带“http://”等协议的绝对URL
return 403;
}

location /glpt/
{
proxy_pass http://192.168.1.209:8088/PRO_GLPT/;
proxy_redirect http:// https://;
proxy_set_header Host $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_next_upstream error timeout invalid_header;
}
if ($request_uri ~* ^(/REDIS/))
{
rewrite ^/REDIS/(.*)$ /redis/$1 last;
}

location /gitblit
{
proxy_pass http://192.168.1.209:10101/;
proxy_redirect http:// https://;
proxy_set_header Host $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_next_upstream error timeout invalid_header;
}


location /luac
{
default_type text/html;
#lua_code_cache off;
if ( $request_uri ~* /devc/gzhqr ) {
content_by_lua_file /usr/local/op/lualib/tcode/gzh_info.lua;
#过期时间30天
expires 30d;
}
}

location /comm
{
default_type text/html;
# 设置变量
set $lable 0;
if ($request_uri ~* /main.*/homeinfo) {
set $lable 1;
content_by_lua_file /usr/local/op/lualib/tcode/busi/main/main.lua;
}
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Real-Port $remote_port;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass http://192.168.1.207:8089/TKB_COMMON;
}
# 维护中的页面
location =/stoptaking.html
{
#expires -1;
add_header Cache-Control no-store ;
index stoptaking.html;
}
}

关于最大并发数

并发总数是worker_processesworker_connections 的乘积,即:max_clients = worker_processes * worker_connections

在设置了反向代理的情况下,max_clients = worker_processes * worker_connections / 4 为什么,为什么上面反向代理要除以4,应该说是一个经验值,根据以上条件,正常情况下的Nginx Server可以应付的最大连接数为:2 * 100000= 200000,worker_connections 值的设置跟物理内存大小有关,因为并发受IO约束,max_clients的值须小于系统可以打开的最大文件数,而系统可以打开的最大文件数和内存大小成正比,一般1GB内存的机器上可以打开的文件数大约是10万左右,我们来看看4G内存的VPS可以打开的文件句柄数是多少:

1
2
[root@localhost ~]# cat /proc/sys/fs/file-max
373519

输出 373519,200000 < 373519,即并发连接总数小于系统可以打开的文件句柄总数,这样就在操作系统可以承受的范围之内,所以,worker_connections 的值需根据 worker_processes 进程数目和系统可以打开的最大文件总数进行适当地进行设置,使得并发总数小于操作系统可以打开的最大文件数目,其实质也就是根据主机的物理CPU和内存进行配置,当然,理论上的并发总数可能会和实际有所偏差,因为主机还有其他的工作进程需要消耗系统资源。

重定向问题

1
2
rewrite regex replacement  [flag];
rewrite 正则表达式 替换URL 参数

如果rewrite同一个上下文中有多个这样的正则,匹配会依照rewrite指令出现的顺序先后依次进行下去,匹配到一个之后并不会终止,而是继续往下匹配,直到返回最后一个匹配上的为止。如果想要中止继续往下匹配,可以使用第三个参数flag。

1
2
3
4
5
6
^/PRO_GLPT/(.*)$ /glpt/$1 last
regex:^/PRO_GLPT/(.*)$
replacement /glpt/$1
flag:last
last匹配到之后直接处理,不在匹配上下文中的rewrite,接着用新的URI马上搜寻新的location
break立即停止执行所有当前上下文的rewrite模块指令,break不会搜寻新的location,直接用这个新的URI来处理请求,这样能避免重复rewite。

在server上下文中使用last,而在location上下文中使用break

如果replacement中包含请求参数,那么默认情况下旧URI中的请求参数也会拼接在replacement后面作为新的URI,如果不想这么做,可以在replacement的最后面加上?。

multi_accept

当一个新连接到达时,如果激活了accept_mutex,那么多个Worker将以串行方式来处理,其中有一个Worker会被唤醒,其他的Worker继续保持休眠状态;如果没有激活accept_mutex,那么所有的Worker都会被唤醒,不过只有一个Worker能获取新连接,其它的Worker会重新进入休眠状态,这就是惊群问题。

listen格式

1
2
3
4
5
sten 127.0.0.1:8000;          
listen 127.0.0.1;
listen 8000;
listen *:8000;
listen localhost:8000;

stub_status状态解释

1
2
3
4
5
6
7
8
9
对后端发起的活动连接数                                                                                       
Active connections: 105
server accepts handled requests
#nginx 总共处理了 48509358 个连接, 成功创建 48509358 次握手 (证明中间没有失败的), 总共处理了 50104491 个请求 (平均每次握手处理了 1.03个数据请求)
48509358 48509358 50104491
#Reading:nginx 读取到客户端的Header信息数
#Writing:nginx 返回给客户端的Header信息数
#Waiting:开启 keep-alive 的情况下,这个值等于active - (reading + writing)意思就是Nginx说已经处理完正在等候下一次请求指令的驻留连接
Reading: 0 Writing: 1 Waiting: 103