文章目录
- Linux云计算架构-nginx调优
Linux云计算架构-nginx调优
1. 修改源码隐藏版本号[编译安装前]
# 查看nginx版本及其安装的模块
[root@master ~]# nginx -V
nginx version: nginx/1.19.2
built by gcc 4.8.5 20150623 (Red Hat 4.8.5-36) (GCC)
configure arguments: --prefix=/usr/local/nginx --with-http_dav_module --with-http_stub_status_module --with-http_addition_module --with-http_sub_module --with-http_flv_module --with-http_mp4_module --with-pcre=/usr/local/src/pcre-8.41 --user=nginx --group=nginx
[root@master ~]# nginx -v
nginx version: nginx/1.19.2
# 无隐藏版本信息,查询如下:
[root@master ~]# curl -I 192.168.8.184
HTTP/1.1 200 OK
Server: nginx/1.19.2
Date: Tue, 25 Aug 2020 04:02:21 GMT
Content-Type: text/html
Content-Length: 612
Last-Modified: Tue, 25 Aug 2020 01:43:48 GMT
Connection: keep-alive
ETag: "5f446cd4-264"
Accept-Ranges: bytes
# 编译前隐藏nginx版本号信息,修改三个源码文件
# 修改nginx版本号和软件名称
[root@master ~]# cat -n /usr/local/src/nginx-1.19.2/src/core/nginx.h
13 #define NGINX_VERSION "1.19.2"
14 #define NGINX_VER "nginx/" NGINX_VERSION
# 修改HTTP头信息中的connection字段,防止回显具体版本号
# nginx
[root@master ~]# cat -n /usr/local/src/nginx-1.19.2/src/http/ngx_http_header_filter_module.c
49 static u_char ngx_http_server_string[] = "Server: nginx" CRLF;
# Nginx报404错误时,不回显版本号。
# nginx
[root@master ~]# cat -n /usr/local/src/nginx-1.19.2/src/http/ngx_http_special_response.c
36 "<hr><center>nginx</center>" CRLF
2. 修改nginx运行用户
[root@master ~]# cat -n /usr/local/nginx/conf/nginx.conf
1
2 user nginx nginx; # 运行用户及其用户组
# 动态加载nginx配置文件
[root@master ~]# /usr/local/nginx/sbin/nginx -s reload
# 可以看到运行用户已经改为nginx了
# master process nginx主进程,用于管理nginx的worker进程
# worker process nginx的工作进程,为用户提供服务
[root@master ~]# ps aux | grep nginx
root 29079 0.0 0.0 18256 644 ? Ss 09:51 0:00 nginx: master process /usr/local/nginx/sbin/nginx
nginx 29080 0.0 0.0 20700 1904 ? S 09:51 0:00 nginx: worker process
root 31171 0.0 0.0 112728 984 pts/1 S+ 12:18 0:00 grep --color=auto nginx
3. 设置nginx的cpu亲和力
# 查看cpu内核数量,这里是8核的cpu
[root@master ~]# grep process /proc/cpuinfo
processor : 0
processor : 1
processor : 2
processor : 3
processor : 4
processor : 5
processor : 6
processor : 7
[root@master ~]# grep process /proc/cpuinfo | wc -l
8
# 修改worker_processes为8个工作进程
[root@master ~]# vim /usr/local/nginx/conf/nginx.conf
3 worker_processes 8;
[root@master ~]# /usr/local/nginx/sbin/nginx -s reload
# 可以看到有8个工作进程
[root@master ~]# ps aux | grep nginx
root 22550 0.0 0.1 18296 1400 ? Ss 16:12 0:00 nginx: master process /usr/local/nginx/sbin/nginx
nginx 23876 0.0 0.1 20792 1404 ? S 17:13 0:00 nginx: worker process
nginx 23877 0.0 0.1 20792 1404 ? S 17:13 0:00 nginx: worker process
nginx 23878 0.0 0.1 20792 1396 ? S 17:13 0:00 nginx: worker process
nginx 23879 0.0 0.1 20792 1416 ? S 17:13 0:00 nginx: worker process
nginx 23881 0.0 0.1 20792 1416 ? S 17:13 0:00 nginx: worker process
nginx 23883 0.0 0.1 20792 1416 ? S 17:13 0:00 nginx: worker process
nginx 23884 0.0 0.1 20792 1416 ? S 17:13 0:00 nginx: worker process
nginx 23885 0.0 0.1 20792 1416 ? S 17:13 0:00 nginx: worker process
root 23890 0.0 0.0 112724 988 pts/0 S+ 17:13 0:00 grep --color=auto nginx
# 查看进程父子关系
[root@master ~]# pstree -p | grep nginx
|-nginx(22550)-+-nginx(23876)
| |-nginx(23877)
| |-nginx(23878)
| |-nginx(23879)
| |-nginx(23881)
| |-nginx(23883)
| |-nginx(23884)
| `-nginx(23885)
# 为配置cpu亲和力,测试如下,可以看到23876这个工作进程可以在8个cpu上面运行,即cpu上下文会进行切换,带来额外开销。
[root@master ~]# taskset -cp 23876
pid 23876's current affinity list: 0-7
# 设置cpu的亲和力,即是把每个nginx工作进程绑定到固定的cpu上,从而减少cpu上下文切换导致的额外开销。
# 8核设置如下:
2 user nginx;
3 worker_processes 8;
4 worker_cpu_affinity 00000001 00000010 00000100 00001000 00010000 00100000 01000000 10000000;
# 4核设置如下:
worker_cpu_affinity 0001 0010 0100 1000;
[root@master ~]# /usr/local/nginx/sbin/nginx -s reload
# 可以看到每个工作进程都只能使用1个cpu
[root@master ~]# pstree -p | grep nginx
|-nginx(22550)-+-nginx(24183)
| |-nginx(24185)
| |-nginx(24186)
| |-nginx(24187)
| |-nginx(24188)
| |-nginx(24189)
| |-nginx(24190)
| `-nginx(24191)
[root@master ~]# taskset -cp 24183
pid 24183's current affinity list: 0
[root@master ~]# taskset -cp 24190
pid 24190's current affinity list: 6
4. 设置每个worker进程最多打开的文件数
# 1个nginx工作进程最多可以打开的文件数=最多打开的文件数/nginx工作进程数,即(ulimit -n)/worker_processes
# 查看最多可以打开的文件数
[root@master ~]# ulimit -n
1024
# 修改最大进程数和最大文件数,退出当前终端即可生效。
[root@master ~]# vim /etc/security/limits.conf
* soft noproc 102400
* hard noproc 102400
* soft nofile 102400
* hard nofile 102400
# 临时生效
[root@master ~]# ulimit -n 102400
[root@master ~]# ulimit -n
102400
# 修改nginx配置文件的1个工作进程最多可以打开的文件数为102400,一般与ulimit -n相同。
[root@master ~]# vim /usr/local/nginx/conf/nginx.conf
5 worker_rlimit_nofile 102400;
5. 修改nginx事件处理模型和单个进程最大连接数
nginx下的IO多路复用有三种机制,分别是select
、poll
、epoll
。IO多路复用通过某一种机制,监视多个描述符,当某个描述符就绪,就会通知程序对齐进行读写操作。
epoll的优点:
①无最大并发连接的限制,上限是最大可以打开文件的数目。该数字一般大于2048且与内存有关。
# epoll上限具体数值
[root@master ~]# cat /proc/sys/fs/file-max
377834f
②epoll只在乎活跃的连接有多少,而不在乎连接总数有多少。故效率远高于其他两种机制。可以看作是共享内存。
# 修改IO多路复用的机制
16 events {
17 use epoll;
18 worker_connections 102400;
19 }
# worker_connections:指单个工作进程可以允许同时建立外部连接的数量。无论这个连接外部主动建立的,还是内部建立的。一个工作进程建立一个连接后,进程将打开一个文件副本。
# worker_connections的值还受限于操作系统ulimit -n设定的值和nginx的worker_connections 的值。一般情况下,ulimit -n、worker_rlimit_nofile、worker_connections三者的值是一样的。
[root@master ~]# nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
[root@master ~]# /usr/local/nginx/sbin/nginx -s reload
# 查看下每个nginx进程占用内存的大小。为42096kb。
[root@master ~]# top -u nginx
PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND
9562 nginx 20 0 221208 6640 1324 S 0.0 0.2 0:00.02 php-fpm
9565 nginx 20 0 221208 6640 1324 S 0.0 0.2 0:00.02 php-fpm
21598 nginx 20 0 61292 42096 748 S 0.0 1.1 0:00.29 nginx
21599 nginx 20 0 61292 42096 748 S 0.0 1.1 0:00.29 nginx
21600 nginx 20 0 61292 42096 748 S 0.0 1.1 0:00.32 nginx
21601 nginx 20 0 61292 42096 748 S 0.0 1.1 0:00.28 nginx
21602 nginx 20 0 61292 42096 748 S 0.0 1.1 0:00.29 nginx
21603 nginx 20 0 61292 42096 748 S 0.0 1.1 0:00.30 nginx
21604 nginx 20 0 61292 42096 748 S 0.0 1.1 0:00.30 nginx
21605 nginx 20 0 61292 42096 748 S 0.0 1.1 0:00.29 nginx
6. 修改ServerName和location
# ServerName可以写什么?这里建议写IP地址或精准匹配
①精准匹配 www.abong.com
②左模糊 *.abong.com
③右模糊 www.*
④正则表达式
⑤default_server
⑥服务IP地址 192.168.8.184
# 修改ServerName
[root@master ~]# vim /usr/local/nginx/conf/nginx.conf
40 server {
41 listen 80;
42 server_name 192.168.8.184;
[root@master ~]# nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
[root@master ~]# /usr/local/nginx/sbin/nginx -s reload
# location匹配
= 绝对匹配
^~ url前半部分匹配,不进行正则
~ 正则匹配,区分大小写
~* 正则匹配,不区分大小写
\ 转义
* 任意字符
$ 以什么结尾
# ~ \.php$ 匹配url以php结尾的文件,且区分大小写
# 注释取消掉,然后该脚本文件名为$document_root
[root@master ~]# vim /usr/local/nginx/conf/nginx.conf
70 location ~ \.php$ {
71 root html;
72 fastcgi_pass 127.0.0.1:9000;
73 fastcgi_index index.php;
74 fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
75 include fastcgi_params;
76 }
7. 开启高效传输模式
[root@master ~]# vim /usr/local/nginx/conf/nginx.conf
32 sendfile on; # 开启高效文件传输模式。on表示调用sendfile函数来发送文件;
# 普通应用为on,磁盘IO负载中设为off。图片显示不正常设为off;
33 tcp_nopush on; # 当sendfile为on时,防止网络阻塞,积极减少网络报文段数量
# tcp_nopush on; #防止网络阻塞
# tcp_nodelay on; #防止网络阻塞
8. 设置连接超时时间
keepalive_timeout
的设置主要是为了保护服务器资源【cpu、内存、控制连接数】。客户端和服务器之间建立连接,会消耗服务器资源,该参数的设置是为了断掉那些处于等待状态的连接,以释放服务器资源。
[root@master ~]# vim /usr/local/nginx/conf/nginx.conf
36 keepalive_timeout 65; # 客户端连接保持会话的时间,单位s
37 tcp_nodelay on; # 防止网络阻塞,在keepalive_timeout下才有效
38 client_header_timeout 15; # 客户端请求头读取超时时间,超时将返回request time out的错误。
39 client_body_timeout 15; # 客户端请求主体超时时间,超时将返回request time out的错误。
40 send_timeout 15; # 客户端响应时间,两次活动的时间间隔超过这个时间,nginx将断开连接。
# 当客户端停止访问时,允许nginx服务器关闭连接,释放socket资源。
reset_timedout_connection on;
# 可以设置php上传附件的文件大小
client_max_body_size 10m;
[root@master ~]# nginx -t
[root@master ~]# /usr/local/nginx/sbin/nginx -s reload
9. fastcgi调优
fastcgi
是一种协议,规定了fastcgi应用和支持fastcgi的web服务器之间的接口。fastcgi是动态服务和静态服务的接口,以二进制连续传递。目的是为了改善网站的性能,减少资源占用,提高访问速度。
cache 写入缓存区
buffer 读取缓存区
fastcgi 动态服务和静态服务的接口
# fastcgi各参数介绍
fastcgi_connect_timeout 300; #指定链接到后端FastCGI的超时时间。
fastcgi_send_timeout 300; #向FastCGI传送请求的超时时间,这个值是指已经完成两次握手后向 FastCGI传送请求的超时时间。
fastcgi_read_timeout 300; #指定接收FastCGI应答的超时时间,这个值是指已经完成两次握手后接收 FastCGI应答的超时时间。
fastcgi_buffer_size 64k; #指定读取FastCGI应答第一部分需要用多大的缓冲区,这个值表示将使用1个64KB的缓冲区读取应答的第一部分(应答头),可以设置为gastcgi_buffers选项指定的缓冲区大小.
fastcgi_buffers 4 64k; #指定本地需要用多少和多大的缓冲区来缓冲FastCGI的应答请求,如果一个php脚本所产生的页面大小为256KB,那么会分4个64KB的缓冲区来缓存,如果页面大小大于256KB,那么大于256KB的部分会缓存到fastcgi_temp_path指定的路径中,但是这并不是好方法,因为内存中的数据处理速度要快于磁盘。一般这个值应该为站点中php脚本所产生的页面大小的中间值,如果站点大部分脚本所产生的页面大小为 256KB,那么可以把这个值设置为“8 16K”、“4 64k”等。
fastcgi_busy_buffers_size 128k; #建议设置为fastcgi_buffer的两倍,繁忙时候的buffer。
fastcgi_temp_file_write_size 128k; #在写入磁盘fastcgi_temp指定的路径时,将用多大的数据库容量,默认值是fastcgi_buffers的两倍,设置上述数值设置小时若负载上来时可能报502Bad Gatewnay。
fastcgi_cache ngnix; #表示开启FastCGI缓存并为其指定一个名称。开启缓存非常有用,可以有效降低CPU的负载,并且防止502的错误发生,但是开启缓存也可能会引起其他问题,要很据具体情况选择。
fastcgi_cache_valid 200 302 1h; #用来指定应答代码的缓存时间,实例中的值表示将200和302应答缓存一小时,要和fastcgi_cache配合使用。应答代码即使状态码。
fastcgi_cache_valid 301 1d; #将301应答缓存一天。
fastcgi_cache_valid any 1m; #将其他应答缓存为1分钟。
fastcgi_cache_min_uses 1; #请求的数量。请求1次就不再缓存。
fastcgi_cache_path /tmp/nginx_cache #定义缓存的路径。
fastcgi_temp_path /tmp/nginx_cache # 定义临时缓存路径,用于缓存大于fastcgi_buffers的部分,一般不用。
fastcgi_cache_use_stale
fastcgi_cache_key
keys_zone=nginx:512m # 定义缓存区域名称,缓存大小为512m
inactive=1d max_size=5G; # 不活动的数据缓存1天,缓存大小为5G。
实战设置:
# location匹配
= 绝对匹配
^~ url前半部分匹配,不进行正则
~ 正则匹配,区分大小写
~* 正则匹配,不区分大小写
\ 转义
* 任意字符
$ 以什么结尾
#http标签下生产设置:
fastcgi_connect_timeout 300;
fastcgi_send_timeout 300;
fastcgi_read_timeout 300;
fastcgi_buffer_size 64k;
fastcgi_buffers 4 64k;
fastcgi_busy_buffers_size 128k;
fastcgi_temp_file_write_size 128k;
fastcgi_cache_path /tmp/nginx_cache levels=2:2
keys_zone=nginx:512m
inactive=1d max_size=5G;
# location匹配
= 绝对匹配
^~ url前半部分匹配,不进行正则
~ 正则匹配,区分大小写
~* 正则匹配,不区分大小写
\ 转义
* 任意字符
$ 以什么结尾
# server下location生产设置:
location ~ .*\.(php|php5)?$
{
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
include fastcgi.conf;
fastcgi_cache nginx;
fastcgi_cache_valid 200 302 1h;
fastcgi_cache_valid 301 1d;
fastcgi_cache_valid any 1m;
fastcgi_cache_min_uses 1;
fastcgi_cache_use_stale error timeout invalid_header http_500;
fastcgi_cache_key http://$host$request_uri;
}
# 配置完毕一定要检查是否语法错误,避免无法加载nginx配置文件。
[root@master ~]# nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
[root@master ~]# /usr/local/nginx/sbin/nginx -s reload
10. gzip压缩网页调优
使用gzip
压缩功能,节约带宽,节约成本,加快传输速度,让用户有更好的体验。但是使用gzip压缩是会消耗cpu的,故cpu较大时使用该gzip功能较合适。
nginx启用压缩功能需要加载ngx_http_gzip_module
模块;
apache启动压缩功能需要加载mod_deflate
模块。
【压缩:文本、js、html、css】
【不压缩:图片、视频、flash】
gzip on; #开启压缩功能。
gzip_min_length 1k; #设置允许压缩的页面最小字节数,页面字节数从header头的Content-Length(内容长度)中获取,默认值是0,不管页面多大都进行压缩,建议设置成大于1K,如果小与1K可能会越压越大。 gzip_buffers 4 32k; #压缩缓冲区大小,表示申请4个单位为 32K的内存作为压缩结果流缓存,默认值是申请与原始数据大小相同的内存空间来存储gzip压缩结果。
gzip_http_version 1.1; #压缩版本(默认1.1,前端为squid2.5时使用1.0)用于设置识别HTTP协议版本,默认是 1.1,目前大部分浏览器已经支持GZIP解压,使用默认即可。
gzip_comp_level 9; #压缩比例,用来指定GZIP压缩比,1压缩比最小,处理速度最快,9压缩比最大,传输速度快,但是处理慢,也比较消耗CPU资源。
gzip_types text/css text/xml application/javascript; #用来指定压缩的类型,‘text/html’ 类型总是会被压缩.
gzip_vary on; #vary header支持,该选项可以让前端的缓存服务器缓存经过GZIP压缩的页面,例如用Squid缓存经过nginx压缩的数据。
# 生产设置:
[root@master ~]# vim /usr/local/nginx/conf/nginx.conf
gzip on;
gzip_min_length 1k;
gzip_buffers 4 32k;
gzip_http_version 1.1;
gzip_comp_level 9;
gzip_types text/css text/xml application/javascript;
gzip_vary on;
[root@master ~]# nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is succes
[root@master ~]# /usr/local/nginx/sbin/nginx -s reload
11. expires缓存调优
对图片、css、js等更新频率较低的元素使用缓存,第一次加载慢一点,但是第二次就会很快了。
不希望缓存的内容:
①广告图片
②网络流量统计工具
③更新频繁的文件
# location匹配
= 绝对匹配
^~ url前半部分匹配,不进行正则
~ 正则匹配,区分大小写
~* 正则匹配,不区分大小写
\ 转义
* 任意字符
$ 以什么结尾
# 以下缓存设置都是在server下设置
# 对某种类型的文件进行缓存
location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$
{
expires 365d;
}
location ~ .*\.(js|css)?$
{
expires 30d;
}
# 对某个目录下的文件进行缓存
location ~ ^/(images|javascript|js|css|flash|media|static)/
{
expires 360d;
}
# 对某个文件进行缓存
location ~(test.txt)
{
expires 7d;
break;
}
缓存的优缺点:
优点:缩短服务的响应时间、减轻服务器负担、减少网络带宽使用量,降低企业成本。
缺点:若被缓存的内容更新了,客户端无法及时看到最新的内容。
解决方法:缩短缓存时间、更改缓存对象的名字、客户端可通过清理缓存看到最新的内容。
12. nginx日志优化
12.1 日志切割优化
对访问日志和错误日志一天一压缩,仅保留10天数据。
# 时间调整
[root@master ~]# date
2020年 08月 26日 星期三 14:45:24 CST
[root@master ~]# echo $(date +%F)
2020-08-26
[root@master ~]# echo $(date +%F -d -1day)
2020-08-25
[root@master ~]# echo $(date +%F -d 1day)
2020-08-27
[root@master logs]# cd /usr/local/nginx/logs/
[root@master logs]# vim log_cut.sh
#!/bin/bash
# 日志切割脚本
date=$(date +%F -d -1day)
cd /usr/local/nginx/logs
if [ ! -d cut ] ; then
mkdir cut
fi
mv access.log cut/access_$(date +%F -d -1day).log
mv error.log cut/error_$(date +%F -d -1day).log
/usr/local/nginx/sbin/nginx -s reload
tar -cjvf cut/$date.tar.bz2 cut/*
rm -rf cut/access* && rm -rf cut/error*
cat >>/var/spool/cron/root<<eof
00 00 * * * /bin/sh /usr/local/nginx/logs/cut_nginx_log.sh >/dev/null 2>&1
eof
find -type f -mtime +10 | xargs rm -rf
[root@master logs]# chmod +x log_cut.sh
不把图片信息记录到访问日志中:
[root@master logs]# vim /usr/local/nginx/conf/nginx.conf
location ~ .*\.(js|jpg|jpeg|JPG|JPEG|css|bmp|gif|GIF)$ {
access_log off;
}
[root@master logs]# nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
日志目录权限优化:
[root@master ~]# chown -R root:root /usr/local/nginx/logs/
[root@master ~]# chmod -R 777 /usr/local/nginx/logs/
日志格式优化:
# 访问日志格式:
# 日志格式取消注释即可
log_format access '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
1.$remote_addr与$http_x_forwarded_for用以记录客户端的ip地址;
2.$remote_user:用来记录客户端用户名称;
3.$time_local:用来记录访问时间与时区;
4.$request:用来记录请求的url与http协议;
5.$status:用来记录请求状态,正常是200;
6.$body_bytes_s ent :记录发送给客户端文件主体内容大小;
7.$http_referer:用来记录从哪个页面链接访问过来的;
8.$http_user_agent:记录客户端浏览器的相关信息;
# 定义日志存放路径:
# access_log 路径 日志级别
access_log logs/nginx/access.log main
access_log logs/host.access.404.log log404;
12.2 目录文件访问控制
主要功能是禁止目录下指定文件被访问,也可以是禁止所有文件被访问。
# 拒绝所有人访问images目录下的某些文件
[root@master ~]# vim /usr/local/nginx/conf/nginx.conf
location ~ ^/images/.*\.(php|php5|.sh|.py|.pl)$
{
deny all;
}
[root@master ~]# nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
[root@master ~]# /usr/local/nginx/sbin/nginx -s reload
[root@master ~]# mkdir /usr/local/nginx/html/images/
[root@master ~]# echo "<?php phpinfo(); ?>" >> /usr/local/nginx/html/images/index.php
[root@master ~]# ll /usr/local/nginx/html/images/index.php
-rw-r--r--. 1 root root 20 8月 26 15:00 /usr/local/nginx/html/images/index.php
访问网站:http://192.168.8.184/images/index.php
,如果看到以下界面,应该就是未安装php。
如果安装了php的,未拒绝应该会显示如下界面:
设置了拒绝,应该显示如下:
如果显示正常,可以检查下location是不是有允许php的。
# d1目录和d2目录下的文件被拒绝访问
location ~ ^/images/(d1|d2)/.*\.(php|php5|.sh|.py|.py)$
{
deny all;
}
# 访问txt文件或doc文件,会被重定向到百度
location ~* \.(txt|doc)$
{
if ( -f $request_filename) {
root /usr/local/nginx/html;
rewrite ^/(.*)$ http://www.baidu.com last;
break;
}
}
# 访问test1下的内容,则返回404
# 访问test2下的内容,则返回403
location /test1/ { return 404 ; }
location /test2/ { return 403 ; }
# 不允许访问test下的内容
location ~ ^/(test)/ {
deny all;
}
12.3 来源访问控制
需要ngx_http_access_module模块支持,默认安装。
# 拒绝192.168.8.网段的主机访问test目录下的内容
location ~ ^/(test)/ {
allow 192.168.8.0/24;
deny all;
}
# 拒绝192.168.8.网段的主机访问网站
location / {
allow 192.168.8.0/24;
deny all;
}
# 当192.168.8.185访问网站时,显示404
location / {
if ( $remote_addr = 192.168.8.185 )
{
return 404;
}
}
13. 禁止使用IP访问网站
# 使用IP访问,跳转到百度
server {
listen 80;
server_name 192.168.8.184;
rewrite ^ http://www.baidu.com$request_uri?;
# 使用IP访问,跳转到403
server {
listen 80;
server_name 192.168.8.184;
return 403;
# 301跳转,使用域名访问。
# abong.com会跳转到www.abong.com
listen 80;
root /usr/share/nginx/html/;
server_name www.abong.com abong.com;
if ($host = 'abong.com'){
rewrite ^/(.*)$http://www.abong.com/$1 permanent;
}
14. 防盗链
防止别人直接从你的网站引用图片等链接,消耗服务器的资源和网络流量。
解决方法:
①图片加水印
②防火墙,控制访问IP
③防盗链策略
# 访问图片返回404
location ~* \.(jpg|gif|png|swf|flv|wma|wmv|asf|mp3|mmf|zip|rar)$ {
valid_referers none blocked *.abong.com abong.com;
if ($invalid_referer) {
return 404;
}
}
# 访问图片重定向到其他页面(跳转页面)
location ~* \.(jpg|gif|png|swf|flv|wma|wmv|asf|mp3|mmf|zip|rar)$ {
valid_referers none blocked *.abong.com abong.com;
if ($invalid_referer) {
rewrite ^/ http://www.abong.com/img/nolink.png;
}
}
# 在server中设置错误页面
# error_page 状态码 页面
error_page 404 /404.html;
15. 开启登录认证功能
# 修改nginx配置文件,支持登录认证功能。
[root@master ~]# vim /usr/local/nginx/conf/nginx.conf
location / {
root html;
auth_basic "my site";
auth_basic_user_file /usr/local/nginx/conf/passwd;
index index.html index.htm;
}
# 创建登录用户,需要httpd-tools包支持
[root@master ~]# yum install httpd-tools -y
[root@master ~]# htpasswd -cm /usr/local/nginx/conf/passwd abong
New password:
Re-type new password:
Adding password for user abong
[root@master ~]# htpasswd -m /usr/local/nginx/conf/passwd test
New password:
Re-type new password:
Adding password for user test
[root@master ~]# cat /usr/local/nginx/conf/passwd
abong:$apr1$leIUQGWv$.SgSU6/.xP6k0TAOfQMOJ/
test:$apr1$BHgJNkv0$.nEDOO/ciGK0reU2SLOMK.
# 设置密码文件权限,只允许nginx用户读
[root@master ~]# chmod 400 /usr/local/nginx/conf/passwd
[root@master ~]# chown nginx:nginx /usr/local/nginx/conf/passwd
[root@master ~]# /usr/local/nginx/sbin/nginx -s reload
# 如果没有显示认证界面,注意是不是location配置冲突了。
16. 防止DDOS攻击
DDOS攻击即洪水攻击,指的是网站同一时刻被访问了很多次,占用了大量的系统资源。这里限制某一时刻客户端与服务端只能建立1次连接。
# 需要加载ngx_http_limit_conn_module模块,默认是没有的。这里就不演示了,生产环境中常用防火墙去控制。
[root@master ~]# cd /usr/local/src/nginx-1.19.2/
[root@master nginx-1.19.2]# ./configure --help | grep limit
--without-http_limit_conn_module disable ngx_http_limit_conn_module
--without-http_limit_req_module disable ngx_http_limit_req_module
--without-stream_limit_conn_module disable ngx_stream_limit_conn_module
# 限流设置如下:
[root@master ~]# vim /usr/local/nginx/conf/nginx.conf
# http标签设置
limit_conn_zone $binary_remote_addr zone=addr:10m; # 定义一个以源IP地址为标识的限制连接区域(共享内存区),区域名为addr,区域大小为10m
# server设置
location / {
root html;
limit_conn addr 1; # 限制连接1次,即每次只能建立一次连接。
index index.html index.htm;
}
[root@master ~]# nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
# 一秒并发2次连接,一次成功连接200,一次丢失请求503
[root@master ~]# ab -c 2 -t 1 http://192.168.8.184/test/index.html
# 可以通过访问日志查看
tail -f /usr/local/nginx/logs/access.log
17. 反向代理参数说明
# location块可对指定目录或者文件进行访问控制
# proxy_set_header设置请求头所包含的内容
# 以下配置是反向代理的标准配置,需要设置3个proxy_set_header
location / {
index index.html index.htm index.jsp; # 支持代理的文件类型。
proxy_pass http://192.168.8.184; # 后端服务器地址或者后端服务器集群地址
proxy_set_header Host $host:$server_port; # 代理服务器的主机名和端口号,默认是proxy_pass的值。
proxy_set_header X-Real-IP $remote_addr; # 从web服务器上获取远程客户端的IP地址
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; # 获取远程客户端IP地址
}
18. 其他参数说明
# 错误日志格式:
# error_log 路径 日志级别
#日志级别:[ debug | info | notice | warn | error | crit ]
error_log logs/error.log;
#error_log logs/error.log notice;
#error_log logs/error.log info;
# nginx进程文件
pid logs/nginx.pid;
# 配置http服务器
http{
server_tokens off; # 隐藏nginx版本信息
include mime.types; # 文件扩展名与文件类型映射表
default_type application/octet-stream; # 默认文件类型
#charset utf-8; # 默认编码
# server_names_hash_bucket_size 128; # 服务器名字的hash表大小
# client_header_buffer_size 32k; # 上传文件大小限制
server {
# 一个server就是一个虚拟主机
listen 80; # 监听端口号
server_name 192.168.8.184; # 域名,存在多个可用空格隔开。
client_header_buffer_size 4k; # 客户端请求头部的缓冲区大小,小头
large_client_header_buffers 4 128k; # 客户端请求头部的缓冲区大小,大头
client_max_body_size 300m; # 允许客户端请求的最大单文件字节数
client_body_buffer_size 128k; # 缓冲区代理缓冲客户端请求的最大字节数
proxy_connect_timeout 600; # nginx与后端服务器连接超时时间
proxy_read_timeout 600; # 连接成功后,后端服务器响应时间
proxy_send_timeout 600; # 连接成功后,请求发送到后端服务器超时时间
proxy_buffer_size 64k; # nginx代理服务器报错用户头信息的缓冲区大小
proxy_buffers 4 32k; # 缓冲区大小,4个32k的空间
proxy_busy_buffers_size 64k; # 高负荷下缓冲区大小,一般为proxy_buffers的2倍
proxy_temp_file_write_size 64k; # 设置缓存文件夹大小,大于这个值,直接从upstream后端服务器传数据。
# proxy_temp_path和proxy_cache_path要在同一分区
proxy_temp_path /data/proxy_temp_dir # 临时文件存放路径
proxy_cache_path /data/proxy_cache_dir # 缓冲文件存放路径
# 内存缓冲空间名为cache_one,大小为200M,缓存时间为1天。
# 硬盘缓存空间大小为30G
keys_zone=cache_one:200m inactive=1d max_size=30g;
client_body_buffer_size 512k; # 客户端请求页面主体大小,默认是系统页面大小的2倍,8k或者16k。
proxy_intercept_errors on; # 是否使用nginx拦截应答代码为400及以上应答。
location /nginxstatus{
# location块设置
stub_status on; # 获取nginx状态
access_log on; # 把nginx状态信息记录到访问日志中
}
}
}
以上就是nginx调优的基本内容了,具体使用还是要结合生产环境实验。
授人以鱼不如授人以渔!!!nginx调优很重要!!!