Nginx通用配置

获取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
# global

# 4
stream {
...
}
# 7
http {
...
server {
...
location / {
root
index
}
}

server {
...
location / {
root
index
}
}
}

types {
...
}


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
[root@nginx-2 ~]# nginx -T
# 语法检查
nginx: the configuration file /apps/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /apps/nginx/conf/nginx.conf test is successful

# 配置文件/apps/nginx/conf/nginx.conf
# configuration file /apps/nginx/conf/nginx.conf:


####################### 全局段 #######################
#user nobody;
worker_processes 1;

#error_log logs/error.log;
#error_log logs/error.log notice;
#error_log logs/error.log info;

#pid logs/nginx.pid;

####################### 事件配置段 #######################
events {
worker_connections 1024;
}

####################### http配置段 #######################
http {
####################### 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"';

#access_log logs/access.log main;

sendfile on;
#tcp_nopush on;

#keepalive_timeout 0;
keepalive_timeout 65;

#gzip on;
####################### server配置段 #######################
server {
####################### 虚拟主机配置 #######################
listen 80;
server_name localhost;

#charset koi8-r;

#access_log logs/host.access.log main;

####################### location配置段 #######################
location / {
####################### url配置 #######################
root html;
index index.html index.htm;
}

#error_page 404 /404.html;

# redirect server error pages to the static page /50x.html
#
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root 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$ {
# 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;
#}
}


# another virtual host using mix of IP-, name-, and port-based configuration
#
#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;
# 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;
# }
#}

}

# configuration file /apps/nginx/conf/mime.types:

types {
text/html html htm shtml;
text/css css;
text/xml xml;
image/gif gif;
image/jpeg jpeg jpg;
application/javascript js;
application/atom+xml atom;
application/rss+xml rss;

text/mathml mml;
text/plain txt;
text/vnd.sun.j2me.app-descriptor jad;
text/vnd.wap.wml wml;
text/x-component htc;

image/avif avif;
image/png png;
image/svg+xml svg svgz;
image/tiff tif tiff;
image/vnd.wap.wbmp wbmp;
image/webp webp;
image/x-icon ico;
image/x-jng jng;
image/x-ms-bmp bmp;

font/woff woff;
font/woff2 woff2;

application/java-archive jar war ear;
application/json json;
application/mac-binhex40 hqx;
application/msword doc;
application/pdf pdf;
application/postscript ps eps ai;
application/rtf rtf;
application/vnd.apple.mpegurl m3u8;
application/vnd.google-earth.kml+xml kml;
application/vnd.google-earth.kmz kmz;
application/vnd.ms-excel xls;
application/vnd.ms-fontobject eot;
application/vnd.ms-powerpoint ppt;
application/vnd.oasis.opendocument.graphics odg;
application/vnd.oasis.opendocument.presentation odp;
application/vnd.oasis.opendocument.spreadsheet ods;
application/vnd.oasis.opendocument.text odt;
application/vnd.openxmlformats-officedocument.presentationml.presentation
pptx;
application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
xlsx;
application/vnd.openxmlformats-officedocument.wordprocessingml.document
docx;
application/vnd.wap.wmlc wmlc;
application/wasm wasm;
application/x-7z-compressed 7z;
application/x-cocoa cco;
application/x-java-archive-diff jardiff;
application/x-java-jnlp-file jnlp;
application/x-makeself run;
application/x-perl pl pm;
application/x-pilot prc pdb;
application/x-rar-compressed rar;
application/x-redhat-package-manager rpm;
application/x-sea sea;
application/x-shockwave-flash swf;
application/x-stuffit sit;
application/x-tcl tcl tk;
application/x-x509-ca-cert der pem crt;
application/x-xpinstall xpi;
application/xhtml+xml xhtml;
application/xspf+xml xspf;
application/zip zip;

application/octet-stream bin exe dll;
application/octet-stream deb;
application/octet-stream dmg;
application/octet-stream iso img;
application/octet-stream msi msp msm;

audio/midi mid midi kar;
audio/mpeg mp3;
audio/ogg ogg;
audio/x-m4a m4a;
audio/x-realaudio ra;

video/3gpp 3gpp 3gp;
video/mp2t ts;
video/mp4 mp4;
video/mpeg mpeg mpg;
video/quicktime mov;
video/webm webm;
video/x-flv flv;
video/x-m4v m4v;
video/x-mng mng;
video/x-ms-asf asx asf;
video/x-ms-wmv wmv;
video/x-msvideo avi;
}

版本

1
2
3
4
5
6
7
[root@nginx-2 ~]# nginx -V
nginx version: nginx/1.22.0
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 --user=nginx --group=nginx --with-compat --with-file-aio --with-threads --with-http_addition_module --with-http_auth_request_module --with-http_gunzip_module --with-http_gzip_static_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-stream --with-stream_realip_module --with-stream_ssl_module --with-stream_ssl_preread_module --with-http_geoip_module=dynamic --with-stream_geoip_module=dynamic
[root@nginx-2 ~]#

由nginx -T可以得到几个配置段

  • 全局 nginx配置相关
  • event IO模型配置段
  • http web服务器, http代理
    • server
      • location
  • stream tcp代理

全局配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
user  nginx;
worker_processes auto;
worker_cpu_affinity auto;
error_log logs/error.log error;
pid logs/nginx.pid;
#这个数字包括Nginx的所有连接(例如与代理服务器的连接等),⽽不仅仅是与客户端的连接,另⼀个考虑因素是实际的并发连接数不能超过系统级别的最⼤打开⽂件数的限制.
worker_rlimit_nofile 65536;
#/proc/sys/fs/file-max 所有进程最大的文件数

events {
#设置单个work进程的最大并发连接数 总并发 = worker_connections * worker_processes
worker_connections 10000;
use epoll;
#优化同⼀时刻只有⼀个请求⽽避免多个睡眠进程被唤醒的设置,on为防⽌被同时唤醒,默认为off,全部唤醒的过程也成为"惊群",因此nginx刚安装完以后要进⾏适当的优化。
accept_mutex on;
#Nginx服务器的每个⼯作进程可以同时接受多个新的⽹络连接,但是需要在配置⽂件中配置,此指令默认为关闭,即默认为⼀个⼯作进程只能⼀次接受⼀个新的⽹络连接,打开后⼏个同时接受多个。
multi_accept on;

}

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
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
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"';

#access_log logs/access.log main;
log_format access_json '{"@timestamp":"$time_iso8601",' #访问时间
'"host":"$server_addr",' #访问的nginx主机地址
'"clientip":"$remote_addr",' #访问nginx客户端地址
'"size":$body_bytes_sent,' #传输到客户端的字节数,不算响应头
'"responsetime":$request_time,' #处理请求的时间
'"upstreamtime":"$upstream_response_time",'
'"upstreamhost":"$upstream_addr",'
'"http_host":"$host",' #请求的主机名
'"uri":"$uri",' #uri
'"domain":"$host",'
'"xff":"$http_x_forwarded_for",' #如果用户是从CDN代理转发过来的会显示所有转发的地址
'"referer":"$http_referer",' #显示客户端从那个页面到来的
'"tcp_xff":"$proxy_protocol_addr",' #获取代理访问服务器的客户端地址,如果是直接访问,该值为空字符串
'"http_user_agent":"$http_user_agent",' #客户端信息
'"status":"$status"}'; #状态码
access_log logs/access.log access_json; #使用日志格式

# 第2阶段不等待
sendfile on;
# 场景: 在磁盘上有较⼤⽂件的场合,⽐如视频、⾳频等。当文件大于4M时不会使用sendfile, 不会磁盘加载到内核了,直接读磁盘。第1阶段和第2阶段均省略。
directio 4m;

# 在开启了sendfile的情况下,多个文件合并请求后统⼀发送给客户端。
# 场景: 高并发on减少开销。并发小on有延迟。
tcp_nopush off;

# ⽤asynchronous file I/O(AIO)功能,需要编译开启 --with-file-aio
aio on;


############# 长连接 start #############
# 设置会话保持时间,如果写俩个参数表示, 后面的参数会告诉客户端, 第1个是保持时间
keepalive_timeout 65 65;
# 连接后允许传输的最大文件数量 过小时,一个会话如果达到请求数量,nginx会主动断开连接,造成nginx端出现大量TIME_WAIT
keepalive_requests 2000;
# 在开启了keepalived模式下的连接是否启⽤TCP_NODELAY选项,当为off时,延迟0.2s发送,默认On时,不延迟发送,⽴即发送⽤户相应报⽂。
# 场景: 默认on 等0.2让数据包累积之后发送,高并发减少开销。并发小on有延迟。
tcp_nodelay off;
# 禁用ie6不建立长连接;
keepalive_disable msie6;
############# 长连接 stop #############



############# 压缩 start #############
gzip on;
gzip_comp_level 5;

# IE6 不压缩
gzip_disable "MSIE [1-6]\.";
# 即使http 1.0也支持压缩,默认1.1
gzip_http_version 1.0;

gzip_min_length 1k; # 至少1k文件才压缩
gzip_types text/plain application/json application/javascript application/x-javascript text/cssapplication/xml text/javascript application/x-httpd-php image/jpeg image/gif image/png;
# 压缩打开时, 响应报⽂⾸部插⼊“Vary: Accept-Encoding”
gzip_vary on;
############# 压缩 stop #############

############# 上传优化 start #############

# 设置允许客⼾端上传单个⽂件的最⼤值,默认值为1m
# 如果上传大小超过nginx限制,nginx会返回 413 错误代码
client_max_body_size 1024m;
# 上传请求体大于16k默认值,会文件缓存
client_body_buffer_size 16k;
client_body_temp_path /apps/nginx/client_body_temp 1 2 2;
############# 上传优化 stop #############

############# 文件响应缓存 start #############
# 最大缓存10000个文件,非活动数据超时时长60s
open_file_cache max=10000 inactive=60s;

# 每间隔60s检查⼀下缓存数据有效性
open_file_cache_valid 60s;

# 60秒内⾄少被命中访问5次才被标记为活动数据; 没有5次就是非活动,60s过期。同时会被清理。
open_file_cache_min_uses 5;

# 缓存错误信息
open_file_cache_errors on;

############# 文件响应缓存 stop #############

############# 响应配置 start #############
# 流程 Client -> Nginx
# Nginx响应给客户端时,添加首部
add_header X-cache $upstream_cache_status;
add_header X-Via MageEdu;

# 安全
# 隐藏Nginx server版本。配置在http块中
server_tokens off;

############# 响应配置 stop #############

############# proxy_pass 相关代理配置 start #############
# 流程 Client -> Nginx Proxy -> Real Server
# 当前配置的是 Nginx Proxy -> Real Server

##### 建立连接 ===
# 建立连接版本
proxy_http_version 1.0;

# 建立连接超时,建立失败503
proxy_connect_timeout 60s;
# 读请求的超时, 如果后端mysql查询时间太长, 默认值就会让nginx给用户响应502.
proxy_read_timeout 60s;
# 写请求的超时, 如果后端mysql写入时间太长, 默认值就会让nginx给用户响应502.
proxy_send_timeout 60s;
##### 建立连接 === ~~~

##### 传递首部 ===
# 后端apache: /etc/httpd/conf/httpd.conf LogFormat "%{X-Forwarded-For}i %h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{UserAgent}i\"" combined 其中%{}i 表示引用HTTP首部
# 后端nginx: /apps/nginx/conf/nginx.conf "$http_x_forwarded_for"' #默认⽇志格式就有此配置 http_开头表示引用HTTP首部

# 场景1: 后端需要真实的客户端IP
# Client -> Nginx Proxy -> Real Server(apache, Nginx)
proxy_set_header X-Forwarded-For $remote_addr;
proxy_set_header X-Real-IP $remote_addr;
# Client -> Nginx Proxy1 -> Nginx Proxy2 -> Nginx Proxy2 -> Real Server(apache, Nginx)
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

# 场景2: 后端nginx需要依据Host首部选择虚拟主机
proxy_set_header Host $host;


# 代理模式下,大量转发时,Ngx直接读缓存,直接转发。
# 当设定 proxy_set_header或hide_header,用于保存http报文header的hash表上限。
proxy_headers_hash_bucket_size 128;
# 设定 hash bucket size最大空间。字节
proxy_headers_hash_max_size 512;
# 保存server_name的hash表及上限。字节
server_names_hash_bucket_size 512;
server_names_hash_max_size 512;

##### 传递首部 === ~~~

##### 响应请求 ===
# 默认隐藏后端传递给客户端 “Date”, “Server”, “X-Pad”, and “X-Accel-...” 首部
# 额外定义隐藏,后端本身支持了跨域,nginx处也配置跨域时,需要把后端的跨域首部隐藏. proxy_hide_header Access-Control-Allow-Origin;
#proxy_hide_header field;
# 许可传递后端的首部,从代理服务器传递给客户端. 本来后端默认隐藏server, 现在许可传递Server, 当然这不安全。
#proxy_pass_header field;

# 场景: 客户端发起请求后,主动断开时,nginx如何处理? off,默认配置时, 大量的499表示"当前请求"后端响应慢,用户等的不耐烦了。后端太慢
# 默认off, nginx直接中断client连接,直接记录499响应码。但是后端还在处理请求。
# on表示nginx会忽略客户中断,一直等后端响应。要么200,要么超时502。
proxy_ignore_client_abort off;
##### 响应请求 === ~~~

##### 缓存响应 ===

# 以指定key缓存。默认$scheme$proxy_host$request_uri;
proxy_cache_key $request_uri;
# 定义对特定响应码的响应内容的缓存时⻓. 200 302 301 缓存10m分钟
# any表示除了200,302,301缓存1m.
proxy_cache_valid 200 302 301 10m;
proxy_cache_valid any 1m;

# 缓存的位置
# levels=1:2:2 缓存目录。1表示16进制0-f. 将文件md5从后向前取,第1个为1级子目录,第2-3为2级目录,第4-5为三级目录。加速查找
# proxycache:20m 缓存区域名,大小(主要用来存放key和metadata)
# inactive 缓存有效期
# max_size 占用磁盘空间大小,在inactive时间内,有效缓存, 看会有多少缓存。
proxy_cache_path /apps/nginx/cache/proxy_temp levels=1:2:2 keys_zone=proxycache:20m inactive=120s max_size=1g;


# 后端不可用使用缓存?不需要
# ngx_http_upstream_module 可以4层检查后端,不在线会自动下线。
# 后端全部挂了,zabbix有监控。
# proxy_cache_use_stale error timeout http_500 http_502 http_503 http_504;


##### 缓存响应 === ~~~


############# proxy_pass 相关代理配置 stop #############

############# fastcgi_pass 相关代理配置 start #############
fastcgi_cache_key $request_uri;
fastcgi_cache_path /apps/nginx/cache/fastcgi_temp levels=1:2:2 keys_zone=fastcgicache:20m inactive=120s max_size=1g;
#fastcgi_cache_stale
fastcgi_cache_valid 200 302 301 10m;
fastcgi_cache_valid any 1m;
############# fastcgi_pass 相关代理配置 stop #############

# server 配置独立
include conf.d/*.conf;
}
1
2
3
4
5
6
install -dv cache/{proxy_temp,fastcgi_temp}

[root@localhost ~]# which nginx
/apps/nginx/sbin/nginx
[root@localhost ~]# nginx -t
[root@localhost ~]# systemctl restart nginx

server段配置

基本的web网站

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
[root@localhost nginx]# cat /apps/nginx/conf/conf.d/default.conf 
server {
listen 80;
#listen 443 ssl;
#server_name blog.mykernel.cn www.mykernel.cn mykernel.cn;
# 证书
#ssl_certificate /apps/nginx/certs/4899578_mykernel.cn.pem;
# 私钥
#ssl_certificate_key /apps/nginx/certs/4899578_mykernel.cn.key;
# ssl缓存
#ssl_session_cache shared:sslcache:20m;
# 缓存失效
#ssl_session_timeout 10m;

location / {
#if ( $scheme ~* "http$") {
# rewrite ^(.*)$ https://mykernel.cn$1 permanent;
#}
root /apps/nginx/html/;
}

location ^~ /static/ {
expires 90d; #设置⽂件过期时间
}

location /statics { #旧版本程序中的请求路径需要重写请求路径后再响应给客户端,不需要在跳转⾄其他location
root /apps/nginx/html/;
index index.html;
rewrite ^/statics/(.*) /static/$1 break;
}
}

ssl配置

1
install -dv /apps/nginx/certs

准备ca

1
2
3
private_key=ca.key
certificate=ca.pem
openssl req -x509 -sha256 -days 1825 -newkey rsa:2048 -keyout $private_key -out $certificate -nodes -subj '/C=CN/ST=SC/L=CD/O=OPS/OU=OPS/CN=ca.mykernel.cn' -verbose

准备自己的公钥和秘钥

1
2
openssl req -newkey rsa:4096 -keyout blog.mykernel.key -out blog.mykernel.csr  \
-nodes -days 365 -subj '/C=CN/ST=SC/L=CD/O=OPS/OU=OPS/CN=blog.mykernel.cn' -verbose

签发多域名证书 domain.ext

1
2
3
4
5
6
basicConstraints=CA:FALSE
subjectAltName = @alt_names
[alt_names]
DNS.1 = mykernel.cn
DNS.2 = www.mykernel.cn
DNS.3 = blog.mykernel.cn
1
openssl x509 -req -CA $certificate  -CAkey $private_key -in blog.mykernel.csr -out blog.mykernel.crt -days 365 -CAcreateserial -extfile domain.ext

查看证书

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
[root@localhost ~]# openssl x509 -in blog.mykernel.crt -noout -text | grep  -E -C 3 'Subject|Issuer'
Serial Number:
fb:a6:13:f3:7a:05:4c:ac
Signature Algorithm: sha256WithRSAEncryption
Issuer: C=CN, ST=SC, L=CD, O=OPS, OU=OPS, CN=ca.mykernel.cn # 签发
Validity
Not Before: Jul 9 09:53:41 2022 GMT
Not After : Jul 9 09:53:41 2023 GMT
Subject: C=CN, ST=SC, L=CD, O=OPS, OU=OPS, CN=blog.mykernel.cn
Subject Public Key Info:
Public Key Algorithm: rsaEncryption
Public-Key: (4096 bit)
Modulus:
--

X509v3 Basic Constraints:
CA:FALSE
X509v3 Subject Alternative Name:
DNS:mykernel.cn, DNS:www.mykernel.cn, DNS:blog.mykernel.cn # 多子域名
Signature Algorithm: sha256WithRSAEncryption
25:91:57:9d:d2:00:1f:a6:3c:e6:d9:06:7d:ff:bd:e1:1c:a6:
1
[root@localhost ~]# cp blog.mykernel.crt blog.mykernel.key /apps/nginx/certs/
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
server {
listen 80;
listen 443 ssl;
server_name blog.mykernel.cn www.mykernel.cn mykernel.cn;
# 证书
ssl_certificate /apps/nginx/certs/blog.mykernel.crt;
# 私钥
ssl_certificate_key /apps/nginx/certs/blog.mykernel.key;
# ssl缓存
ssl_session_cache shared:sslcache:20m;
# 缓存失效
ssl_session_timeout 10m;

location / {
if ( $scheme ~* "http$") {
rewrite ^(.*)$ https://blog.mykernel.cn$1 permanent;
}
root /apps/nginx/html/;
index index.html;
try_files $uri/index.html /index.html =404;
}
}

准备域名

1
echo '127.0.0.1  blog.mykernel.cn mykernel.cn www.mykernel.cn' >> /etc/hosts
1
curl --cacert /root/ca.pem -L www.mykernel.cn

alias

1
2
3
4
5
6
7
8
9
location /about {
root /data/nginx/html/; #必须要在cp⽬录中创建⼀个about⽬录才可以访问,否则报错。
index index.html;
}

location /about {
alias /data/nginx/html/abc; #当访问about的时候,会显示alias定义的/data/nginx/html/pc⾥⾯的内容。
index index.html;
}

location优先级

1
2
3
4
5
6
7
8
9
10
=
^~ 前缀
~* 不区分大小写
~ 区分大小写
普通路径匹配 /


# 其他字段
$ 结尾
\ 转义

访问控制

4层

1
2
3
4
5
6
7
location /admin {
alias /data/nginx/html/admin;
index index.html;
allow 192.168.10.1;
deny 10.0.0.0/16;
deny all; #先允许⼩部分,再拒绝⼤部分
}

7层

1
2
3
4
5
6
location = /login {
root /data/nginx/html;
index index.html;
auth_basic "login password";
auth_basic_user_file /apps/nginx/conf/.htpasswd;
}

准备认证文件

1
2
3
4
# httpd-tools
# apache2-utils
htpasswd -cbm /apps/nginx/conf/.htpasswd user1 123456
htpasswd -bm /apps/nginx/conf/.htpasswd user2 123456

自定义错误

1
2
3
4
5
6
7
8
9
10
server  {
error_page 404 /404.html;

# 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;
}
}

自定义访问日志

1
2
3
4
5
server {
server_name mykernel.cn;
access_log /data/nginx/logs/mykernel.cn_access.log; #访问日志
error_log /data/nginx/logs/mykernel.cn_error.log; #错误日志
}

检查文件是否存在

1
2
3
4
5
6
location / {
root /apps/nginx/html/;
index index.html;
#echo $uri;
try_files $uri/index.html /index.html =404;
}

下载服务器

1
2
[root@localhost html]# cd /apps/nginx/html/download/
[root@localhost download]# touch centos{7,8} ubuntu{7,8}
1
2
3
4
5
6
7
8
9
10
location /download {
# ⾃动索引功能
autoindex on;
# 计算⽂件确切⼤⼩(单位bytes),off只显示⼤概⼤⼩(单位kb、mb、gb)
autoindex_exact_size on;
# 显示本机时间⽽⾮GMT(格林威治)时间
autoindex_localtime on;
root /apps/nginx/html/;
limit_rate 10k;
}

image-20220709173501413

nginx状态页

1
2
3
4
5
6
location /nginx_status {
stub_status;
#allow 192.168.10.1;
allow 127.0.0.1;
deny all;
}
1
2
3
4
5
[root@localhost ~]# curl localhost/nginx_status
Active connections: 1
server accepts handled requests
29 29 29
Reading: 0 Writing: 1 Waiting: 0
1
2
3
4
5
6
7
# Active connections:# 在线用户和空闲线程
# accepts: 接受的客户端请求的总数
# handled: 处理完成的客户端请求的总数, 一般和接受一样,除非是worker_connections限制等被拒绝的连接。
# requests: 客户端发来的总的请求数
# Reading: 正在读取客户端请求报⽂⾸部的连接数
# Writing: 正在向客户端发送响应报⽂过程中的连接数
# Waiting: 正在等待客户端发出请求的空闲连接数,开启 keep-alive的情况下,这个值等于active – (reading+writing),

本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!