nginx服务器优化
-
Nginx优化主要从配置文件着手,常见优化参数如下:
-
worker_processes //与CPU核心数量一致
-
worker_connections //每个worker最大并发连接数
-
server_tokens //服务器版本号信息
-
client_header_buffer_size //默认请求包头信息的缓存
-
large_client_header_buffers //大请求包头部信息的缓存个数与容量
-
error_page 404 //自定义404错误页面
-
步骤一:构建Nginx服务器
-
1)源码安装Nginx软件
[[email protected] ~]# yum -y install gcc pcre-devel openssl-devel #安装常见依赖包
[[email protected] ~]# useradd -s /sbin/nologin nginx
[[email protected] ~]# tar -zxvf nginx-1.8.0.tar.gz
[[email protected] ~]# cd nginx-1.8.0
[[email protected] nginx-1.8.0]# ./configure \
> --prefix=/usr/local/nginx \ #指定安装路径
> --user=nginx \ #指定用户
> --group=nginx \ #指定组
> --with-http_ssl_module #开启SSL加密功能
[[email protected] nginx-1.8.0]# make && make install #编译并安装
- 2)启用Nginx服务并查看监听端口状态
[[email protected] ~]# /usr/local/nginx/sbin/nginx
[[email protected] ~]# netstat -anptu | grep nginx
tcp 0 0 0.0.0.0:80 0.0.0.0:* LISTEN 10441/nginx
-
步骤二:优化前从客户机访问Nginx服务器测试
-
1)使用ab高并发测试
[[email protected] ~]# ab –n 2000 –c 2000 http://192.168.4.5/
Benchmarking 192.168.4.5 (be patient)
socket: Too many open files (24) #提示打开文件数量过多
- 2)使用脚本测试长头部请求是否能获得响应
[[email protected] ~]# cat buffer.sh
#!/bin/bash
URL=http://192.168.4.5/index.html?
for i in {1..5000}
do
URL=${URL}v$i=$i
done
curl $URL
[[email protected] ~]# chmod +x buffer.sh
[[email protected] ~]# ./ buffer.sh
.. ..
<center><h1>414 Request-URI Too Large</h1></center> #提示头部信息过大
[[email protected] ~]# firefox http://192.168.4.5/tt.html //访问不存在的页面
-
步骤三:优化Nginx服务器
-
1)修改Nginx配置文件
[[email protected] ~]# vim /usr/local/nginx/conf/nginx.conf
.. ..
worker_processes 2; #与CPU核心数量一致
events {
worker_connections 10000; #每个worker最大并发连接数
use epoll;
}
http {
server_tokens off; #不显示nginx版本号信息
client_header_buffer_size 1k; #默认请求包头信息的缓存
large_client_header_buffers 4 4k; #大请求包头部信息的缓存个数与容量
server {
listen 80;
server_name www.tarena.com;
location / {
root html;
index index.html index.htm;
}
location ~* \.(jpg|jpeg|gif|png|css|js|ico|xml)$ {
expires 30d; #定义客户端缓存时间为30天
}
error_page 404 /40x.html; #自定义错误页面
location = /40x.html {
root html;
}
}
}
- 2)修改Linux操作系统最大打开文件数
通过修改/etc/security/limits.conf文件修改打开文件最大数量:
[[email protected] ~]# vim /etc/security/limits.conf
* soft nofile 100000
* hard nofile 100000
[[email protected] ~]# ulimit –Hn 100000
[[email protected] ~]# ulimit –Sn 100000
- 3)提前生成404错误页面,供测试使用:
[[email protected] ~]# vim /usr/local/nginx/html/40x.html
<h1>~~~~^^^Error^^^~~~</h1>
- 步骤四:优化后从客户机访问Nginx服务器测试
对Nginx服务器进行各种参数优化后,在客户端访问服务器页面,对比优化前与优化后的区别,验证优化是否生效。