Nginx的搭建和优化
一、Nginx简介
1.1概述
Nginx:
- Nginx是一个高性能的HTTP和反向代理服务器。
- 是一款轻量级的高性能的web服务器/反向代理服务器/电子邮件(IMAP/POP3)代理服务器
- 单台物理服务器可支持30 000~50 000个并发请求。
Apache:
- Apache是以进程为基础的结构,进程要比线程消耗更多的系统开支,不太适用于多处理器环境,因此,在一个apache Web站点扩容时,通常是增加服务器或扩充群集节点而不是增加处理器。
1.2 Nginx和Apache的优缺点比较
(1)nginx相对于apache的优点∶
- 轻量级,同样起web服务,比apache占用更少的内存及资源
- 抗并发,nginx处理请求是异步非阻塞的,而apache是阻塞型的在高并发下,nginx能保持低资源低消耗高性能
- 高度模块化的设计,编写模块相对简单
(2)apache相对于nginx的优点∶
- Rewrite比nginx的rewrite强大 (rewrite的主要功能就是实现统一资源定位符URL的跳转)
- 模块多,基本想到的都可以找到
- 少bug, nginx的bug相对较多
- 超稳定
存在的理由:一般来说,需要性能的web服务,用nginx。若不需要性能只求稳定,就选用apache。
nginx进程架构
1.3 ngnix系统命令
# 开机配置
systemctl enable nginx # 开机自动启动
systemctl disable nginx # 关闭开机自动启动
# 启动Nginx
systemctl start nginx # 启动Nginx成功后,可以直接访问主机IP,此时会展示Nginx默认页面
# 停止Nginx
systemctl stop nginx
# 重启Nginx
systemctl restart nginx
# 重新加载Nginx
systemctl reload nginx
# 查看 Nginx 运行状态
systemctl status nginx
# 查看Nginx进程
ps -ef | grep nginx
# 杀死Nginx进程
kill -9 pid # 根据上面查看到的Nginx进程号,杀死Nginx进程,-9 表示强制结束进程
1.4 Nginx 应用程序命令
nginx -s reload *# 向主进程发送信号,重新加载配置文件,热重启*
nginx -s reopen *# 重启 Nginx*
nginx -s stop *# 快速关闭*
nginx -s quit *# 等待工作进程处理完成后关闭*
nginx -T *# 查看当前 Nginx 最终的配置*
nginx -t *# 检查配置是否有问题*
三Nginx的编译安装步骤详解
3.1 关闭防火墙,安装依赖包
1. #关闭防火墙
[root@localhost opt]#systemctl stop firewalld
[root@localhost opt]#systemctl disable firewalld
[root@localhost opt]#setenforce 0
2. #安装依赖关系包
[root@localhost opt]#yum -y install pcre-devel zlib-devel gcc gcc-c++ make
3.2 创建运行用户、组
3.#Nginx服务程序以默认nobody身份运行,建议为其创建专门的用户账号,一边更精准的控制其访问权限
[root@localhost ~]# useradd -M -s /sbin/nologin nginx
3.3 将nginx所需的软件包传到/opt目录下,解压 并编译 安装
4.#切换至opt目录,将下载好的压缩包传进来
[root@localhost opt]#cd /opt
[root@localhost opt]#ls
nginx-1.12.0.tar.gz
5.解压文件
[root@localhost opt]#tar -zxf nginx-1.12.0.tar.gz
[root@localhost opt]#ls
nginx-1.12.0 nginx-1.12.0.tar.gz
6.#切换至解压后的文件夹编译
[root@localhost nginx-1.12.0]#
./configure \
> --prefix=/usr/local/nginx \
> --user=nginx \
> --group=nginx \
>
//解释
--prefix=/usr/local/nginx \
#安装路径
--user=nginx \
#指定用户名
--group=nginx \
#指定用户组
--with-http_stub_status_module
#启用此模块支持状态统计
//
7.#安装
[root@localhost nginx-1.12.0]#make && make install -j4 #开启4核心安装
3.4 做软连接将nginx加入系统环境,并启动nginx
8. #做软连接,让系统识别nginx的操作命令
[root@localhost sbin]#ln -s /usr/local/nginx/sbin/nginx /usr/local/sbin/
9. #检查配置文件是否配置 正确
[root@localhost sbin]#nginx -t
10. #启动nginx
[root@localhost sbin]#nginx
11. #查看是否启动成功
[root@localhost sbin]#ss -ntap|grep nginx
LISTEN 0 128 *:80 *:* users:(("nginx",pid=9123,fd=6),("nginx",pid=9122,fd=6))
nginx-v(大写小写v都可以):查看nginx版本
3.5 管理ngnix的方法(适用于其他软件)
包括检查、启动、停止、重启、查看pid号、重启程序
- 检查
nginx -t #检查配置文件是否配置正确(语法)
- 启动
nginx ##启动nginx
- 查看nginx的pid进程号
cat查看/usr/local/nginx/logs/nginx.pid ##查看nginx安装文件夹内的pid文件,具体目录是自己定义的
ss -ntap | grep nginx
natstat -ntap | grep
ps aux | gerp nginx(重要) ##通过ps命令可以看到nginx有两种,分别是master进程和worker主进程,附进程为worker进程,master进程用来管理worker进程,worker进程用来处理与用户之间的连接
lsof -i :80 ##通过端口号查看文件pid号
- 停止
kill -3 <pid号> ##通过pid号关闭进程
kill -s QUIT <pid号> ##作用同上
killall -3 nginx ##通过进程名称杀掉关于这个进程的所有进程
killall -s QUIT nginx ##作用同上
- 重载程序
kill -1 <pid号> ##在不关闭进程的情况下重新加载程序
kill -s HUB <pid号> ##作用同上
killall -i nginx ##通过进程名称杀死所有进程以及所有相关进程
kullall -s HUB nginx ##作用同上
3.6 编写nginx控制脚本加入chkconfig
chkcongif控制文件位置:/etc/init.d/
##脚本位置放在/etc/init.d/nginx
##目录 /etc/init.d/ 中包含许多系统服务的启动和停止脚本。
[root@localhost init.d]#vim /etc/init.d/nginx
#!/bin/bash
#chkcongfig: 35 99 20
#####上面的不注释,这个在写程序控制脚本的时候一定要加。是为了让chkconfig识别
#####35:在那个runlevel下启动,如果是 - 代表默认的等级(2345)
#####99:在开机启动脚本中的启动顺序(第99个启动)
#####20:在关机时第 20 个停止
#desc: this is nginx control scprit
##注释这是nginx控制脚本
CMD="/usr/local/nginx/sbin/nginx"
PID="/usr/local/nginx/logs/nginx.pid"
case "$1" in
start)
$CMD ##打开nginx的路径
;;
stop)
kill -s QUIT $(cat $pid) ##调用变量pid,生成kill -s QUIT +pid命令
;;
restart)
$0 stop ##利用nginx的路径关闭nginx
$0 start ##利用nginx的路径开启nginx
;;
reload)
kill -s HUB $(cat $PID)
;;
*)
##如果输入的不是上面的选项,则执行
echo "Usage: $0{start|stop|restart|reload"
exit1
esac
*********************************************
脚本结束
[root@localhost init.d]#chmod +x /etc/init.d/nginx
[root@localhost init.d]#chkconfig --add nginx
#讲编写nginx控制脚本加入chkconfig中
[root@localhost init.d]#service nginx start
#开启nginx服务
[root@localhost init.d]#service nginx stop
#关闭nginx服务
3.6 将nginx命令加入systemctl
正在centos7中,我们使用systemctl管理服务,下面操作让nginx服务加入systemctl中,以便我们管理,systemctl管理文置:/usr/lib/systemd/system/
[root@localhost system]#cd /lib/systemd/system
#编写脚本,建议直接复制
[root@localhost system]#vim nginx.service
[Unit]
Description=nginx
After=network.target
[Service]
Type=forking
PIDFile=/usr/local/nginx/logs/nginx.pid
ExecStart=/usr/local/nginx/sbin/nginx
ExecReload=/usr/bin/kill -s HUP $MAINPID
ExecStop=/usr/bin/kill -s QUIT $MAINPID
PrivateTmp=true
[Install]
WantedBy=multi-user.target
[root@localhost system]#systemctl daemon-reload
##磁盘上的nogin服务更改,运行'systemctl daemon-reload'重新加载单元。
[root@localhost system]#systemctl start nginx
##启动服务
systemctl和chkconfig最好不要混用,可能会发生错误
比如用chkconfig打开服务,用chkconfig关闭服务
四. 认识nginx的主配置文件nginx.conf
- 文件位置:vim /usr/local/nginx/conf/nginx.conf
文件分为一下几块:
- 全局块:全局配置,对全局生效;
- events块:配置影响Nginx服务器与用户的网络连接;
- http块:配置代理,缓存,日志定义等绝大多数功能和第三方模块的配置:
- server块:配置虚拟主机的相关参数,一个http块中可以有多个server块;
- location块:用于配置匹配的uri;
- upstream:配置后端服务器具体地址,负载均衡配置不可或缺的部分。
4.1 全局配置块
从配置文件开始到events块开始之前的内容,都属于全局块,在全局块中配置的都是影响Nginx整体运行的配置。比如说:worker(工作进程)的数量,错误日志的位置等
#user nobody; #运行用户,若编译时未指定则默认为 nobody
worker_ processes 1; #工作运行数量,一般设置为和CPU核数一样
#error_log logs/error.log; #错误日志文件的位置
#pid logs/nginx.pid; #PID文件的位置
4.2 events配置块(i/o事件配置)
events块主要影响nginx服务器与⽤户的⽹络连接,⽐如worker_connections 1024,标识每个 workderprocess进程⽀持的最⼤连接数为1024
events {
use epoll; #使用 epoll 模型,2.6及以上版本的系统内核,建议使用 epoll 模型以提高性能(默认是没有的,我们通常会添加,可以实现i/o多路复用)
worker_connections 4096; #每个进程处理 4096 个连接
}
#如提高每个进程的连接数还需执行“ulimit -n 65535”命令临时修改本地每个进程可以同时打开的最大文件数。
#在Linux 平台上,在进行高并发TCP连接处理时,最高的并发数量都要受到系统对用户单一进程同时可打开文件数量的限制(这是因为每个TCP连接都要创建一个socket句柄,每个socket句柄同时也是一个文件句柄)。
#可使用ulimit -a 命令查看系统允许当前用户进程打开的文件数限制。
- 查看内核版本号
uname-r- 查看发行版本号
cat /etc/*releas
查看http最大连接数=
woker_connections(每个工作进程的连接数量)*worker_ processes 1(cpu核数)查看cpu数量 两种方法
- top命令查看
- cat /proc/cpuinfo
cpuinfo中的processor: 系统中逻辑处理核的编号。对于单核处理器,则课认为是其CPU编号,对于多核处理器则可以是物理核、或者使用超线程技术虚拟的逻辑核
physical id:processor :逻辑cpu数量
设置进程最大连接数 (系统端)
如提高每个进程的连接数还需执行“ulimit -n 65535”命令临时修改本地每个进程可以同时打开的最大文件数(也就是系统允许打开的最大文件数),可使用ulimit -a 命令查看系统允许当前用户进程打开的文件数限制,但是这只是临时修改,如果想要永久修改系统配置,需要在/etc/security/limits.conf添加文件,保存后立即生效 。
设置nginx的最大连接数,需要
4.3 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;
##此项允许或禁止使用socket的TCP_CORK的选项(发送数据包前先缓存数据),此选项仅在使用sendfile的时候使用
#tcp_nopush on;
##连接保持超时时间,单位是秒
#keepalive_timeout 0;
keepalive_timeout 65; #连接保持超时
##gzip模块设置,设置是否开启gzip压缩输出
#gzip on;
##web 服务的监听配置 ##一个网站站点就是一个sever块
server {
listen 80; #监听地址及端口
server_name www.gcc.com; #站点域名,可以有多个,用空格隔开
#charset utf-8; #网页的默认字符集
location / { #根目录配置
root html; #网站根目录的位置/usr/local/nginx/html
index index.html index.htm; #设置首页文件名,如果网站首页名称没有自动以,就优先寻找index开头的文件
}
##内部错误的反馈页面
error_page 500 502 503 504 /50x.html;
##错误页面配置
location = /50x.html {
root html;
}
}
}
4.4 日志格式设定
4.1.1 常见配置选项:
$remote_addr 与 $http_x_forwarded for用以记录客户端的ip地址;
sremote_user:用来记录客户端用户名称;
stime_local: 用来记录访问时间与时区;
$request: 用来记录请求的url与http协议;
$status: 用来记录请求状态;成功是200,
$body_bytes_sent:记录发送给客户端文件主体内容大小;
$http_referer:用来记录从哪个页面链接访问过来的;
$http_user_agent:记录客户浏览器的相关信息;
通常web服务器放在反向代理的后面,这样就不能获取到客户的IP地址了,通过$remote_add拿到的IP地址是反向代理服务器的iP地址。反向代理服务器在转发请求的http头信息中,可以增加x_forwarded_for信息,用以记录原有客户端的IP地址和原来客户端的请求的服务器地址。
location常见配置指令, root, alias, proxy_pass
root (根路径配置) :请求www.gcc.com/test/1.jpg,会返回文件/usr/local/nginx/html/test/1.jpg
alias (别名配置) :请求www.gcc.com/test/1.jpg,会返回文件/usr/local/nginx/html/1.jpg
proxypass (反向代理配置)
proxy_pass http://127.0.0.1:8080/; 会转发请求到http://127.0.0.1:8080/1.jpg
proxy_ pass http://127.0.0.1:8080; 会转发请求到http://127.0.0.1:8080/test/1.jpg
4.1.2 新增html网页文件
配置好了nginx,在网页上输入我们的ip地址或者输入我们自定义的网址(这里指的是本机访问),默认显示的是/usr/local/nginx/html目录下的index.html文件,这里我们新建一个/test/test.html/文件并用本机访问
location块使用root
cd /usr/local/nginx/html/
[root@localhost html]# ls
50x.html index.html
[root@localhost html]# mkdir test
[root@localhost html]# echo 'this is my test web' > test/test.html
4.2.3 location的匹配规则(优先级)
location后面的内容适用于匹配root访问根目录后面的url路径的,默认root配置选项下,先匹配location后面的路径,在匹配root后的路径
##第一条location规则
location / {
root /usr/local/nginx.html;
index index.html index.htm;
}
#第二条location规则
location /test {
root /data;
index index.html index.htm;
}
下面输入的网址各自都按照哪条规则走,访问那个root路径呢?
首先需要看location后面指定的url路径
1.http://192.168.159.104/test.html 访问路径:/usr/lcoal/nginx/html/test/html
2.http://192.168.159.104/test/test/html 访问路径:/data/test/test/html
##匹配location第二条规则,因为第二条规则使用了前置匹配,有我们需要访问的test目录
4.2.4 location常见配置选项root与alias有什么不同?
上面的方法是使用root的方法添加html网页路径,下面说一下root和alias配置选项的区别
root与alias主要区别在于nginx如何解释location后面的uri,这会使两者分别以不同的方式将请求映射到服务器文件上。
- root的处理结果是:root路径+location路径
- alias的处理结果是:使用alias路径替换location路径
##第一条location规则
location / {
root /usr/local/nginx/html;
index index.html index.htm;
}
#第二条location规则
location /test {
alias /var/www/html/;
index index.html index.htm;
}
下面输入的网址各自都按照哪条规则走,访问那个root路径呢?
1.http://192.168.159.104/ky18.html 实际访问路径:/usr/local.nginx/html/ky18.html
##输入以上的网址,会匹配第一条规则,因为在192.168.159.104后面,没有文件夹,是直接访问ky18.html文件
所以匹配第一条规则
2.http://192.168.159.104/test/ky18.html 实际访问路径:/var/www/html/ky18.html
##输入以上的网址,会匹配第二条规则,因为有/test目录,但是这里使用了alias配置选项,所有并不会访问`/var/www/html/test/ky18.html`
而是把/test转换为别名/var/www/html/
注意: \1. 使用alias时,目录名后面一定要加"/"。 \3. alias在使用正则匹配时,必须捕捉要匹配的内容并在指定的内容处使用。 \4. alias只能位于location块中。(root可以不放在location中)
4.5 访问状态统计配置
1、先使用命令/usr/local/nginx/sbin/nginx -V 查看已安装的 Nginx 是否包含 HTTP_STUB_STATUS 模块
2、修改 nginx.conf 配置文件,指定访问位置并添加 stub_status 配置
cd /usr/local/nginx/conf
cp nginx.conf nginx.conf.bak
vim /usr/local/nginx/conf/nginx.conf
......
http {
......
server {
listen 80;
server_name localhost;
charset utf-8;
##添加 stub_status 配置##
location /status { #访问位置为/status
stub_status on; #打开状态统计功能
access_log off; #关闭此位置的日志记录
}
}
}
- nginx -t检查主配置文件的语法
- 重启服务,访问测试
[root@localhost conf]# systemctl restart nginx
- 可curl -Ls http://192.168.159.104/status 结合awk与if 语句在字符界面更加方便的进行性能监控。
[root@localhost conf]# curl -Ls http://192.168.159.104/status
Active connections: 1
server accepts handled requests
2 2 2
Reading: 0 Writing: 1 Waiting: 0
- Active connections(当前的活动连接数)是一个非常重要的标准,下面的脚本可以用来实时监控这一指标
[root@localhost conf]# CON=$( curl -Ls http://192.168.159.104/status |awk '/Active connections:/{print $3}')
[root@localhost conf]# if [ $CON -gt 25000 ];then
> echo "警告,当前并发数量为 $CON ,超过预警值!"
> fi
五. 基于授权的访问控制
5.1 生成用户密码认证文件
yum install -y httpd-tools
htpasswd -c /usr/local/nginx/passwd.db zhangsan
chown nginx /usr/local/nginx/passwd.db 修改文件的归属
chmod 400 /usr/local/nginx/passwd.db 保护数据文件的安全设置为400,只有nginx和管理员用户才能访问,必须要操作,不修改400的话,执行的时候会报错
5.2 修改主配置文件相对应目录,添加认证配置项
vim /usr/local/nginx/conf/nginx.conf
location /status {
stub_status on;
access_log off;
}
##添加以下部分
location /test { #匹配的根目录文件文件夹名称
root html; #相当于想要保密的文件位置,只有访问这个位置是,才需要用户输入密码
index index.html index.htm;
auth_basic "Hello every body!"; ##弹出的指示语
auth_basic_user_file /usr/local/nginx/userlist.txt; ##
} ##前面设置的密码文件位置
- 检查nginx主配置文件是否有语法错误并重启nginx
- 网页测试
六. 基于客户端的访问控制
访问控制规则如下:
- deny IP/IP段:拒绝某个 IP 或 IP段的客户端访问
- allow IP/IP段:允许某个 IP 或IP 段的客户端的访问
- 规则从上往下执行,如匹配则停止,不再往下匹配
6.1 修改配置文件,添加deny或allow
vim /usr/local/nginx/conf/nginx.conf
location /test {
root html;
index index.html index.htm;
auth_basic "Hello every body!";
auth_basic_user_file /usr/local/nginx/userlist.txt;
##添加以下配置
deny 192.168.159.101; ##允许此ip访问
}
systemctl restart nginx
6.2 重新开了一台ip地址为192.168.159.101的虚拟机,看是否可以访问
- 可以访问默认主页
- 但是无法访问test/test.html,
6.3 反向验证一下,我们允许192.168.159.101这个ip访问,看一下是否可以访问成功
- 修改过nginx配置文件,重启一下nginx服务
[root@localhost test]# systemctl restart nginx
- 用192.168.159.101虚拟机访问192.168.104/test/test.html域名,如果访问成功则说明设置正确
访问成功!!!
七. 基于域名的 Nginx 虚拟主机
- 恢复nginx主配置文件(因为前面的操54可能会影响,故恢复初始设置)
[root@localhost /]# cd /usr/local/nginx/conf/
[root@localhost conf]# ls
fastcgi.conf koi-win scgi_params
fastcgi.conf.default mime.types scgi_params.default
fastcgi_params mime.types.default uwsgi_params
fastcgi_params.default nginx.conf uwsgi_params.default
koi-utf nginx.conf.default win-utf
[root@localhost conf]# cp nginx.conf.default nginx.conf ##用nginx.conf.default覆盖nginx.conf配置文件
cp:是否覆盖"nginx.conf"? yes
7.1 虚拟主机提供域名解析
echo "192.168.217.100 www.kgc.com www.accp.com" >> /etc/hosts
7.2 为虚拟主机准备网页文档
mkdir -p /var/www/html/song
mkdir -p /var/www/html/accp
echo "<h1> www.kgc.com</h1>" >/var/www/html/song/index.html
echo "<h1> www.accp.com</h1>" >/var/www/html/accp/index.html
7.3
这里注意root访问目录前面一定要/
vim /usr/local/nginx/conf/nginx.conf
……
http {
……
server {
listen 80;
server_name www.kgc.com; #设置域名www.kgc.com
charset utf-8;
access_log logs/www.kgc.access.log; #修改单独的日志文件,方便查看
location / {
root /var/www/html/kgc; #设置www.song.com的工作目录
index index.html index.htm;
}
error_page 500 502 503 504 /50x.html;
location = 50x.html{
root html;
}
}
36和56行复制到80行下面
在命令行模式输入 :36,56 co 80
server {
listen 80;
server_name www.accp.com; ##设置域名www.accp.com,注意,需要把之前main给删除
charset utf-8;
access_log logs/www.accp.access.log; ##修改单独的日志文件,方便查看
location / {
root /var/www/html/accp;
index index.html index.htm;
}
error_page 500 502 503 504 /50x.html;
location = 50x.html{
root html;
}
} ##,复制过来以后最后添加一个}
nginx -t #检查语法
systemctl restart nginx
浏览器访问:
http://www.kgc.com
http://www.accp.com
八. 基于不同IP的虚拟主机
说白了就是基于不同的ip地址建立网站,这里注意,使用的ip地址必须要是本机已经存在的ip的,我们在下面选择新建一个临时的ip地址,在设置好后,用域名仍然是可以访问的
现在我的IP地址只有一个192.168.159.104
下面临时新建一个
ifconfig ens33:0 192.168.159.200
8.1 修改主配置文件
8.2 nginx -t检查配置文件并且尝试用ip访问
九. 基于不同端口的虚拟主机
与基于不同的ip基本操作一样,只需要将listen后面的:80端口改成我们想要的端口就可以了
9.1 修改listen项
9.2 nginx-t查看配置文件是否有错误并尝试访问
[root@www html]# 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@www html]# systemctl restart nginx
总结:
- 轻量级,nginxt比apache占用更少的内存及资源:
- 静态处理,Nginx静态处理性能比Apache高;
- Nginx可以实现无缓存的反向代理加速,提高网站运行速度;
- Nginx的性能和可伸缩性不依赖于硬件,Apache依赖于硬件;
- Nginx支持热部署,启动速度迅速,可以在不间断服务的情况下,对软件版本或者配置进行升级;
- nginx是异步进程,多个连接可以对应一个进程:apache是同步多进程,一个连接对应一个进程:
- Nginx高度模块化,编写模块相对简单,且组件比Apache少 高并发下nginx能保持低资源低消耗高性能;
- nginx配置简洁,Apache配置复杂。
\