一、Nginx简介
1.1 概述
Nginx:
- Nginx是一个高性能的HTTP和反向代理服务器。
- 是一款轻量级的高性能的web服务器/反向代理服务器/电子邮件(IMAP/POP3)代理服务器
- 单台物理服务器可支持30 000~50 000个并发请求。
Apache:
Apache是以进程为基础的结构,进程要比线程消耗更多的系统开支,不太适用于多处理器环境,因此,在一个apache Web站点扩容时,通常是增加服务器或扩充群集节点而不是增加处理器。
1.2 Nginx和Apache的优缺点比较
nginx相对于apache的优点∶
轻量级,同样起web服务,比apache占用更少的内存及资源
抗并发,nginx处理请求是异步非阻塞的,而apache是阻塞型的在高并发下,nginx能保持低资源低消耗高性能
高度模块化的设计,编写模块相对简洁
apache相对于nginx的优点∶
- Rewrite比nginx的rewrite强大 (rewrite的主要功能就是实现统一资源定位符URL的跳转)
- 模块多,基本想到的都可以找到
- 少bug, nginx的bug相对较多
- 超稳定
存在的理由:一般来说,需要性能的web服务,用nginx。若不需要性能只求稳定,就选用apache。
1.3 Nginx作为web服务器与Apache比较
相比apache,nginx使用更少的资源,支持更多的并发连接,体现更高的效率。
Nginx作为负载均衡服务器:nginx既可以在内部直接支持rails和php程序对外进行服务,也可以支持http代理服务器对外进行服务。
Nginx采用C进行编写,不论是系统资源开销还是CPU使用效率都比较好。
作为邮件代理服务器:最早开发这个产品的目的之一也是作为邮件代理服务器。
1.4 nginx和apache的配置比较
nginx配置简洁, apache较复杂
1.5 Nginx和Apache的差异
apache是同步多进程模型,一个连接对应一个进程,nginx是异步的,多个连接可以对应一个进程。
Nginx处理静态文件好,耗费内存少,只适合静态和反向。
Apache在处理动态有优势,
nginx并发性比较好,CPU占用内存低,如果rewrite频繁,选用apache最佳。
二、Linux中的I/O
I/O在计算机中指Input/Output,lOPS (Input/Output Per Second)即每秒的输入输出量(或读写次数),是衡量磁盘性能的主要指标之一。IOPS是指单位时间内系统能处理的I/O请求数量,一般以每秒处理的IO请求数量为单位,I/O请求通常为读或写数据操作请求。
一次完整的I/O是用户空间的进程数据与内核空间的内核数据的报文的完整交换,但是由于内核空间与用户空间是严格隔离的,所以其数据交换过程中不能由用户空间的进程直接调用内核空间的内存数据,而是需要经历一次从内核空间中的内存数据copy到用户空间的进程内存当中,所以简单说I/O就是把数据从内核空间中的内存数据复制到用户空间中进程的内存当中。
磁盘I/O:buff/cache 的区别
网络I/O:一切皆文件,本质为对socket文件的读写
获取请求数据,客户端与服务器建立连接发出请求,服务器接受请求
构建响应,当服务器接收完请求,并在用户空间处理客户端的请求,直到构建响应完成
返回数据,服务器将已构建好的响应再通过内核空间的网络I/0发还给客户端
同步/异步:关注的是消息通信机制,即调用者在等待一件事情的处理结果时,被调用者是否提供完成状态的通知。
同步: synchronous,被调用者并不提供事件的处理结果相关的通知消息,需要调用者主动询问事情是否处理完成
异步: asynchronous,被调用者通过状态、通知或回调机制主动通知调用者被调用者的运行状态
三、Nginx的编译安装与启动停止
1.编译安装与启动
1. #关闭防火墙
[root@localhost opt]# systemctl stop firewalld
[root@localhost opt]# setenforce 0
2. #安装依赖关系包
[root@localhost opt]# yum -y install pcre-devel zlib-devel gcc gcc-c++ make
3. #新建用户 nginx 服务程序默认 以 nobody 身份运行,建议为其创建专门的用户账户,以便更准确的控制访问权限
[root@localhost opt]# useradd -M -s /sbin/nologin nginx
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 \
> --with-http_stub_status_module
#解释
--prefix=/usr/local/nginx \ ###安装路径
--user=nginx \ ###指定用户名
--group=nginx \ ###指定用户组
--with-http_stub_status_module ###启用此模块支持状态统计
7.#安装
[root@localhost nginx-1.12.0]# make && make install -j4
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))
1. #关闭防火墙
[root@localhost opt]# systemctl stop firewalld
[root@localhost opt]# setenforce 0
2. #安装依赖关系包
[root@localhost opt]# yum -y install pcre-devel zlib-devel gcc gcc-c++ make
2.停止nginx
1. #先查看nginx的PID号
[root@localhost sbin]# cat /usr/local/nginx/logs/nginx.pid
9122
2.#直接杀死
kill -3 <PID号>
[root@localhost sbin]# kill -3 9122
#就查不到进程了
[root@localhost logs]# ss -ntap|grep nginx
#一定要杀父进程,杀死子进程是没用的
#查进程号
[root@localhost logs]# lsof -i :80
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
nginx 10298 root 6u IPv4 68323 0t0 TCP *:http (LISTEN)
nginx 10299 nginx 6u IPv4 68323 0t0 TCP *:http (LISTEN)
#查看主进程
[root@localhost logs]# cat /usr/local/nginx/logs/nginx.pid
10298
#杀死子进程
[root@localhost logs]# kill -3 10299
#进程没有杀死
[root@localhost logs]# cat /usr/local/nginx/logs/nginx.pid
10298
#杀死父进程
[root@localhost logs]# kill -3 10298
#进程杀死了
[root@localhost logs]# cat /usr/local/nginx/logs/nginx.pid #进程杀死了
cat: /usr/local/nginx/logs/nginx.pid: 没有那个文件或目录
3.添加nginx系统服务
#编写脚本内容如下
[root@localhost init.d]# vim /etc/init.d/nginx
cmd="/usr/local/nginx/sbin/nginx"
pid="/usr/local/nginx/logs/nginx.pid"
start)
$cmd
;;
stop)
kill -3 `cat $pid`
;;
restart)
$0 stop
$0 start
;;
reload)
kill -1 `cat $pid`
;;
*)
echo "please input,start,reload,restart "
exit 0
;;
esac
exit 1
#执行脚本
[root@localhost init.d]# chmod +x /etc/init.d/nginx
[root@localhost init.d]# chkconfig --add nginx
#启动nginx
[root@localhost init.d]# service nginx start
#关闭nginx
[root@localhost init.d]# service nginx stop
4.将nginx命令加入服务
[root@localhost system]# cd /lib/systemd/system
#编写脚本,建议直接复制
[root@localhost system]# vim nginx.service
#!/bin.bash
[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
##磁盘上的ngin服务更改,运行'systemctl daemon-reload'重新加载单元。
[root@localhost system]# systemctl daemon-reload
##启动服务
[root@localhost system]# systemctl start nginx
5.查看nginx版本信息
[root@localhost system]# nginx -v
nginx version: nginx/1.12.0
四、Nginx配置文件
4.1 查看nginx服务的主配置文件
[root@localhost system]# vim /usr/local/nginx/conf/nginx.conf
4.2 全局配置
[root@localhost system]# vim /usr/local/nginx/conf/nginx.conf
#user nobody; ###运行用户
worker_processes 1; ###工作进程数,可配置成服务器内核数*2,如果网站访问量不大,一般设为1就够用了
#error_log logs/error.log; ###错误日志文件的位置
#pid logs/nginx.pid; ###PID文件的位置
4.3 I/O 事件配置
events {
use epoll; ###使用 epoll 模型以提高性能,2.6 以上版本建议使用
worker_connections 4096; ###每个进程处理4096个连接
}
epoll(socket描述符)是Linux内核]为处理大批量文件描述符而作了改进的poll,是Linux下多路复用IO接口select/poll的增强版本,它能显著提高程序在大量并发连接中只有少量活跃的情况下的系统CPU利用率
若工作进程数为 8,每个进程处理 4 096 个连接,则允许 Nginx 正常提供服务的连接数 已超过 3 万个(4 096×8=32 768),当然具体还要看服务器硬件、网络带宽等物理条件的性 能表现。
如提高每个进程的连接数还需执行"ulimit -n 65535"命令临时修改本地每个进程可以同时打开的最大文件数。
在Linux平台.上,在进行高并发TCP连接处理时,最高的并发数量都要受到系统对用户单一进程同时可打开文件数量的限制(这是因为系统为每个TCP连接都要创建一个socket句柄,每个socket句柄同时也是一个文件句柄)。
可使用ulimit -a命令查看系统允许当前用户进程打开的文件数限制。
#查看系统允许当前用户进程打开的文件数
[root@localhost conf]# ulimit -a
core file size (blocks, -c) 0
data seg size (kbytes, -d) unlimited
scheduling priority (-e) 0
file size (blocks, -f) unlimited
pending signals (-i) 6911
max locked memory (kbytes, -l) 64
max memory size (kbytes, -m) unlimited
open files (-n) 1024
pipe size (512 bytes, -p) 8
POSIX message queues (bytes, -q) 819200
real-time priority (-r) 0
stack size (kbytes, -s) 8192
cpu time (seconds, -t) unlimited
max user processes (-u) 6911
virtual memory (kbytes, -v) unlimited
file locks (-x) unlimited
#临时修改本地每个进程可以同时打开的最大文件数
[root@localhost conf]# ulimit -n 6000
#查看修改后的
[root@localhost conf]# ulimit -a
core file size (blocks, -c) 0
data seg size (kbytes, -d) unlimited
scheduling priority (-e) 0
file size (blocks, -f) unlimited
pending signals (-i) 6911
max locked memory (kbytes, -l) 64
max memory size (kbytes, -m) unlimited
open files (-n) 6000
pipe size (512 bytes, -p) 8
POSIX message queues (bytes, -q) 819200
real-time priority (-r) 0
stack size (kbytes, -s) 8192
cpu time (seconds, -t) unlimited
max user processes (-u) 6911
virtual memory (kbytes, -v) unlimited
file locks (-x) unlimited
4.3 http配置
使用“http { }”界定标记,包括访问日志、HTTP 端口、网页目录、默认字符集、连接保 持,以及后面要讲到的虚拟 Web 主机、PHP 解析等一系列设置,其中大部分配置语句都包 含在子界定标记“server { }”内
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 on; ###gzip模块设置,设置是否开启gzip压缩输出
server {
listen 80; ###监听地址及端口
server_name www.kk.com; ###站点域名,可以有多个,用空格隔开
#charset utf-8; ###网页的默认字符集
#access_log logs/host.access.log main;
location / { ###根目录配置
root html; ###网站根目录的位置/usr/local/nginx/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;
}
日志格式设定:
$remote_addr与$http_x_forwarded_for用以记录客户端的ip地址;
$remote_user:用来记录客户端用户名称;
$time_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(根路径配置):root /var/www/html
请求www.kk.com/test/1.html,会返回文件/var/www/html/test/1.html
alias(别名配置):alias /var/www/html
请求www.kk.com/test/1.html,会返回文件/var/www/html/kk/1.html
proxy_pass(反向代理配置)
4.4 访问状态统计配置
nginx 内置了 HTTP_STUB_STATUS 状态统计模块,用来反馈当前的 Web 访问情况, 配置编译参数时可添加–with-http_stub_status_module 来启用此模块支持,可以使用命令
可以使用命令/usr/local/nginx/sbin/nginx –v 查看已安装的 Nginx 是否包含 HTTP_STUB_STATUS 模块。
操作步骤:
1.修改 nginx.conf 配置文件,指定访问位置并添加 stub_status 配置(修改之前进行备份)
#先拷贝一份配置文件
[root@localhost conf]#cp /usr/local/nginx/conf/nginx.conf nginx.conf.bak
# 修改 nginx.conf 配置文件
[root@localhost conf]#vim /usr/local/nginx/conf/nginx.conf
events {
use epoll;
worker_connections 1024;
}
server {
listen 80;
server_name www.kk.com;
charset utf-8;
location / {
root html;
index index.html index.htm;
}
location /status { ###访问位置为/status
stub_status on; ###打开状态统计功能
access_log off; ###关闭此位置的日志记录
}
2.在网页中输入 192.168.146.10/status 测试
Active connections: 2 ###当前活动链接数
server accepts handled requests ###表示已经处理的连接信息
2 2 4 ###三个数字依次表示已处理的连接数、成功的TCP握手次数、已处理的请求数
Reading: 0 Writing: 1 Waiting: 1
3.结合awk来写shell脚本,如果链接数过高报警
#/bin/bash
a=$(curl 192.168.146.10/status)
b=$(echo $a|awk '{print $3}')
if [ $b -ge 1000 ]
then
echo "连接数过高"|mail -s test 1943466298@qq.com
else
echo "运行良好"
fi
4.5 基于授权密码的访问控制
1.生成用户密码认证文件
#安装工具
[root@localhost conf]# yum install -y httpd-tools
#如果没有密码则设置
[root@localhost conf]# htpasswd -c /usr/local/nginx/passwd.db zhangsan
#第二次不用加-c
[root@localhost conf]# htpasswd /usr/local/nginx/passwd.db lisi
[root@localhost conf]# chown nginx /usr/local/nginx/passwd.db
[root@localhost conf]# chmod 400 /usr/local/nginx/passwd.db
2.修改主配置文件相对应目录,添加认证配置项
location /status {
#添加密码认证
auth_basic "secret";
auth_basic_user_file /usr/local/nginx/passwd.db;
# stub_status on;
# access_log off;
root html;
index index.html index.htm;
}
3.重启服务
[root@localhost conf]# nginx -t
[root@localhost conf]# systemctl restart nginx.service
4.在网页测试
http://192.168.146.10 需要输入账号和设置的密码才能登录
4.6 基于客户端的访问控制
基于客户端的访问控制是通过客户端 IP 地址,决定是否允许对页面访问。Nginx 基于 客户端的访问控制要比 Apache 简单,规则如下:
deny IP/IP 段:拒绝某个 IP 或 IP 段的客户端访问。
allow IP/IP 段:允许某个 IP 或 IP 段的客户端访问。
规则从上往下执行,如匹配则停止,不再往下匹配
1.修改配置文件
[root@localhost conf]# vim /usr/local/nginx/conf/nginx.conf
location / {
#auth_basic "secret";
#auth_basic_user_file /usr/local/nginx/passwd.db;
deny 192.168.146.10; ###客户端IP
allow all;
root html;
index index.html index.htm;
}
2.重启服务,访问测试
[root@localhost conf]# nginx -t
[root@localhost conf]# systemctl restart nginx.service
在网页测试时显示 403
被设置的地址拒绝访问
4.7 基于域名的 Nginx 虚拟主机
利用虚拟主机,不用为每个要运行的网站提供一台单独的 Nginx 服务器或单独运行一 组 Nginx 进程,虚拟主机提供了在同一台服务器,同一组 Nginx 进程上运行多个网站的功能。
跟 Apache 一样,Nginx 也可以配置多种类型的虚拟主机,分别是基于 IP 的虚拟主机、 基于域名的虚拟主机、基于端口的虚拟主机。
使用 Nginx 搭建虚拟主机服务器时,每个虚拟 Web 站点拥有独立的“server{}”配置段, 各自监听的 IP 地址、端口号可以单独指定,当然网站名称也是不同的。
1.为虚拟主机提供域名解析
echo "192.168.146.10 www.kk.com www.kkk.com" >> /etc/hosts
2.为虚拟主机准备网页文档
mkdir -p /var/www/html/kk
mkdir -p /var/www/html/kkk
echo "<h1>www.kk.com</h1>" > /var/www/html/kk/index.html
echo "<h1>www.kkk.com</h1>" > /var/www/html/kkk/index.html
3.修改Nginx的配置文件
vim /usr/local/nginx/conf/nginx.conf
http {
server {
listen 80;
server_name www.kk.com; #设置域名www.kk.com
charset utf-8;
access_log logs/www.kk.access.log; #设置日志名
location / {
root /var/www/html/kk; #设置www.kk.com 的工作目录
index index.html index.php;
}
error_page 500 502 503 504 /50x.html;
location = 50x.html{
root html;
}
}
server {
listen 80;
server_name www.kkk.com; #设置域名www.kkk.com
charset utf-8;
access_log logs/www.kkk.access.log;
location / {
root /var/www/html/kkk;
index index.html index.php;
}
error_page 500 502 503 504 /50x.html;
location = 50x.html{
root html;
}
}
}
3.重启服务,访问测试
systemctl restart nginx
浏览器访问
http://www.kk.com
http://www.kkk.com
4.8 基于IP 的 Nginx 虚拟主机
1.添加一个虚拟网卡ip
ifconfig ens33:0 192.168.146.11 netmask 255.255.255.0
2.修改Nginx的配置文件
vim /usr/local/nginx/conf/nginx.conf
http {
server {
listen 192.168.146.10:80; #设置监听地址192.168.146.10
server_name www.kk.com;
charset utf-8;
access_log logs/www.kk.access.log;
location / {
root /var/www/html/kk;
index index.html index.php;
}
error_page 500 502 503 504 /50x.html;
location = 50x.html{
root html;
}
}
server {
listen 192.168.146.11:80; #设置监听地址192.168.146.11
server_name www.kkk.com;
charset utf-8;
access_log logs/www.kkk.access.log;
location / {
root /var/www/html/kkk;
index index.html index.php;
}
error_page 500 502 503 504 /50x.html;
location = 50x.html{
root html;
}
}
}
3.重启服务,访问测试
systemctl restart nginx
浏览器访问
http://192.168.146.10
http://192.168.146.11
4.9 基于端口的 Nginx 虚拟主机
1.修改Nginx的配置文件
vim /usr/local/nginx/conf/nginx.conf
http {
server {
listen 192.168.146.10:80; #设置监听80端口
server_name www.kk.com;
charset utf-8;
access_log logs/www.kk.access.log;
location / {
root /var/www/html/kk;
index index.html index.php;
}
error_page 500 502 503 504 /50x.html;
location = 50x.html{
root html;
}
}
server {
listen 192.168.146.10:8080; #设置监听8080端口
server_name www.kkk.com;
charset utf-8;
access_log logs/www.kkk.access.log;
location / {
root /var/www/html/kkk;
index index.html index.php;
}
error_page 500 502 503 504 /50x.html;
location = 50x.html{
root html;
}
}
}
2.重启服务,访问测试
systemctl restart nginx
浏览器访问
http://192.168.146.10:80
http://192.168.146.10:8080