1、Nginx是如何实现高并发的?
service nginx start之后,然后输入#ps -ef|grep nginx,会发现Nginx有一个master进程和若干个worker进程,这些worker进程是平等的,都是被master fork过来的。在master里面,先建立需要listen的socket(listenfd),然后再fork出多个worker进程。当用户进入nginx服务的时候,每个worker的listenfd变的可读,并且这些worker会抢一个叫accept_mutex的东西,accept_mutex是互斥的,一个worker得到了,其他的worker就歇菜了。而抢到这个accept_mutex的worker就开始“读取请求--解析请求--处理请求”,数据彻底返回客户端之后(目标网页出现在电脑屏幕上),这个事件就算彻底结束。
nginx用这个方法是底下的worker进程抢注用户的要求,同时搭配“异步非阻塞”的方式,实现高并发量。
【评析】在nginx.conf里第二行就是work_process,有默认是4的,也可以更改成auto,这个值不是越大越好,要可实际服务器CPU的情况而定,一般是CPU有几个,工作进程就有几个。
2、编写一个Nginx的access模块,要求准许192.168.3.29/24的机器访问,准许10.1.20.6/16这个网段的所有机器访问,准许34.26.157.0/24这个网段访问,除此之外的机器不准许访问。
1
2
3
4
5
6
|
location/{
access 192.168.3.29
/24
;
access 10.1.20.6
/16
;
access 34.26.157.0
/24
;
deny all;
}
|
【评析】防火墙是层层深入的,可以从硬件上用acl(访问控制列表)实现,如果没有钱买一个防火墙,那么还可以在linux上设置iptables,如果iptables不设置,还可以在nginx上设置。
nginx本身工作很少,内部的各个模块是实际的参与工作的,模块英文信息:http://nginx.org/en/docs/
3、给favicon.ico和robots.txt设置过期时间; 这里为favicon.ico为99天,robots.txt为7天并不记录404错误日志
1
2
3
4
5
6
7
8
9
10
|
location ~(favicon.ico) {
log_not_found off;
expires 99d;
break
;
}
location ~(robots.txt) {
log_not_found off;
expires 7d;
break
;
}
|
4、设定某个文件的浏览器缓存过期时间;这里为600秒,并不记录访问日志
1
2
3
4
5
|
location ^~
/html/scripts/loadhead_1
.js {
access_log off;
expires 600;
break
;
}
|
5、只充许固定ip访问网站,并加上密码,设定账号是james,密码是123456
1
2
3
4
5
6
7
|
printf
"james:$(openssl passwd -crypt 123456)\n"
>>
/usr/local/nginx/conf/passwd
location \ {
allow 22.27.164.25;
#允许的ipd
deny all;
auth_basic “KEY”;
#登陆该网页的时候,会有这个“KEY”的提示,提示只能是英文,中文不识别。
auth_basic_user_file
/conf/htpasswd
;
}
|
6、如果访问服务器的ip地址是203.46.97.124的话,给他展现的主页是/123.html,其他人就展现index.html。
1
2
3
4
5
6
7
|
location / {
if
($remote_addr = 203.46.97.124 ) {
rewrite ^.*$
/123
.html;
}
root
/usr/local/nginx/html
;
index index.html;
}
|