Nginx

Nginx介绍

官网:http://nginx.org

Nginx:engine X,2002年,开源,商业版

Nginx是开源,高性能的HTTP和反向代理服务器,邮件代理服务器,通用TCP/UDP代理服务器。

解决了C10K问题(所谓c10k问题,指的是服务器同时支持成千上万个客户端的问题,也就是concurrent 10 000 connection(这也是c10k这个名字的由来)。由于硬件成本的大幅度降低和硬件技术的进步,如果一台服务器同时能够服务更多的客户端,那么也就意味着服务每一个客户端的成本大幅度降低,从这个角度来看,c10k问题显得非常有意义。)

二次开发版:Tengine,OpenResty(章亦春)

正向代理和反向代理

特性:

  模块化设计,较好的扩展性

  高可靠性

  支持热部署:不停机更新配置文件,升级版本,更换日志文件

  低内存消耗:10000个keep-alive连接模式下的非活动连接,仅需2.5M内存

  event-driven,aio,mmap,sendfile

基本功能:

  静态资源的web服务器

  http协议反向代理服务器

  pop3/imap4协议反向代理服务器

  FastCGI(LNMP),uWSGI(python)等协议

  模块化(非DSO),如zip,SSL模块

nginx架构

nginx的程序架构

web服务相关的功能:

  虚拟主机(server)

  支持 keep-alive 和管道连接

  访问日志(支持基于日志缓冲提高其性能)

  url rewirte

  路径别名

  基于IP及用户的访问控制

  支持速率限制及并发数限制

  重新配置和在线升级而无须中断客户的工作进程

  Memcached 的 GET 接口

nginx的程序架构:

master/worker结构

  一个master进程:

  负载加载和分析配置文件、管理worker进程、平滑升级

  一个或多个worker进程

  处理并响应用户请求

  缓存相关的进程:

  cache loader:载入缓存对象

  cache manager:管理缓存对象

nginx模块

nginx高度模块化,但其模块早期不支持DSO机制;1.9.11版本支持动态装载和卸载

模块分类:

1、核心模块:core module

2、标准模块:

  HTTP 模块: ngx_http_*

  HTTP Core modules 默认功能

  HTTP Optional modules 需编译时指定

  Mail 模块 ngx_mail_*

  Stream 模块 ngx_stream_*

3、第三方模块

nginx的功用

  静态的web资源服务器

    html,图片,js,css,txt等静态资源

  结合FastCGI/uWSGI/SCGI等协议反向代理动态资源请求

  http/https协议的反向代理

  imap4/pop3协议的反向代理

  tcp/udp协议的请求转发(反向代理)

nginx的安装

yum安装

~]# yum -y install nginx
~]# nginx #启动服务(和httpd同用80端口)
~]# ss -ntlp #查看端口启用状态
State       Recv-Q Send-Q      Local Address:Port                     Peer Address:Port              
LISTEN      0      128                     *:80                                  *:*                  
users:(("nginx",pid=1516,fd=6),("nginx",pid=1515,fd=6))

也可到官网上配的yum仓库来安装最新版的

[nginx]
name=nginx repo
baseurl=http://nginx.org/packages/centos/7/x86_64/
gpgcheck=0
enabled=1

官方:

http://nginx.org/packages/centos/7/x86_64/RPMS、

Fedora-EPEL:

https://mirrors.aliyun.com/epel/7/x86_64/

编译安装:

~]# yum groupinstall "Development Tools"
~]#yum install pcre-devel openssl-devel zlib-devel
~]#useradd -r nginx #创建系统账户nginx
~]# wget http://nginx.org/download/nginx-1.12.2.tar.gz
~]# tar -xf nginx-1.12.2.tar.gz 
~]# cd nginx-1.12.2/
~]#./configure --prefix=/usr/local/nginx \  #安装路径
  --conf-path=/etc/nginx/nginx.conf \  #主配置文件安装位置
  --error-log-path=/var/log/nginx/error.log \  #错误日志文件安装位置
  --http-log-path=/var/log/nginx/access.log \  #访问日志文件安装位置
  --pid-path=/var/run/nginx.pid \  #指明pid文件安装位置
  --lock-path=/var/run/nginx.lock \  #锁文件安装位置
  --user=nginx \  #指明以那个身份运行worker进程,主控master进程一般由root运行
  --group=nginx \
--with-http_ssl_module \  #表示把指定模块编译进来
--with-http_v2_module \
--with-http_dav_module \
--with-http_stub_status_module \
--with-threads --with-file-aio
~]#make && make install
~]#nging #启动服务

编译安装选项

--prefix=/etc/nginx #安装路径
--sbin-path=/usr/sbin/nginx #指明nginx程序文件安装路径
--conf-path=/etc/nginx/nginx.conf #主配置文件安装位置
--error-log-path=/var/log/nginx/error.log #错误日志文件安装位置
--http-log-path=/var/log/nginx/access.log #访问日志文件安装位置
--pid-path=/var/run/nginx.pid #指明pid文件安装位置
--lock-path=/var/run/nginx.lock #锁文件安装位置
--http-client-body-temp-path=/var/cache/nginx/client_temp #客户端body部分的临时文件存放路径,服务器允许客户端使用put方法提交大数据时,临时存放的磁盘路径
--http-proxy-temp-path=/var/cache/nginx/proxy_temp #作为代理服务器,服务器响应报文的临时文件存放路径
--http-fastcgi-temp-path=/var/cache/nginx/fastcgi_temp #作为fastcgi代理服务器,服务器响应报文的临时文件存放路径
--http-uwsgi-temp-path=/var/cache/nginx/uwsgi_temp #作为uwsgi代理服务器,服务器响应报文的临时文件存放路径
--http-scgi-temp-path=/var/cache/nginx/scgi_temp #作为scgi反代服务器,服务器响应报文的临时文件存放路径
--user=nginx #指明以那个身份运行worker进程,主控master进程一般由root运行
--group=nginx
--with-http_ssl_module #表示把指定模块编译进来

nginx服务的启动 

两种方法启停服务不能混用

1)使用systemctl开启服务

systemctl start nginx
systemctl stop nginx

2)不使用systemctl开启服务

nginx #开启服务
nginx  -s  stop #停止服务
nginx -t   #检查配置文件的语法错误

nginx命令的选项

-h 查看帮助选项
-V 查看版本和配置选项
-t 测试nginx语法错误
-c filename 指定配置文件(default: /etc/nginx/nginx.conf)
-s signal 发送信号给master进程,signal可为:stop, quit, reopen, reload
示例: -s stop 停止nginx -s reload 加载配置文件
-g directives 在命令行中指明全局指令

nginx配置

帮助文档:http://nginx.org/en/docs/ngx_core_module.html
主配置文件:nginx.conf
子配置文件: include conf.d/*.conf (需要自己新建)

默认主页面路径:/usr/share/nginx/html
日志存放路径:/var/log/nginx/{access.log,error.log} (访问日志和错误日志)

注意:
(1) 指令必须以分号结尾
(2) 支持使用配置变量

nginx的主配置文件里的全局配置

1   .worker_processes auto;  (控制开启的worker数,系统默认是自动的根据内核的个数来开启相应个数的work数,可以修改此条命令来设置)

2、pid /PATH/TO/PID_FILE 指定存储nginx主进程PID的文件路径 (此文件为nginx运行时生成的临时文件;作用:当执行nginx -s stop命令时会找到此文件里存放的进程编号然后调用kill命令将其终止)

3、include file | mask 指明包含进来的其它配置文件片断

4、load_module file 模块加载配置文件:/usr/share/nginx/modules/*.conf 指明要装载的动态模块路径: /usr/lib64/nginx/modules

# vim /etc/nginx/nginx.conf
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;

# Load dynamic modules. See /usr/share/nginx/README.dynamic.
include /usr/share/nginx/modules/*.conf;

性能优化相关的配置

1、worker_processes 进程的数量;通常应该为当前主机的cpu的物理核心数 。

 2、worker_cpu_affinity 0010 0100    (此处的二进制数为具体启用的那颗cpu的编号,0010是2号CPU;0100为3号CPU;此条命令是自己添加到配置文件的全局配置里的如上图)

3、worker_priority 10 指定worker进程的nice值,设定worker进程优先级:[-20,20]  (此条命令也是添加到全局配置中的 默认的优先级为0)

4、worker_rlimit_nofile 30000    worker进程所能够打开的文件数量上限. ( 是所有worker打开文件数的总和并不是指的是单个worker所打开文件数 。统默认是没有设置的   。此条命令也是添加到全局配置中的)

事件驱动相关的配置: event

1、worker_connections 15000 每个worker进程所能够打开的最大并发连接数数量 .(指单个worker进程所能接收的并发连接数,和上面的总数相对应就可以了)

2、use method 指明并发连接请求的处理方法 ,默认自动选择最优方法 use epoll; 

3、accept_mutex on | off 互斥 处理新的连接请求的方法;on指由各个worker轮流处理新请求,Off指每个新请 求的到达都会通知(唤醒)所有的worker进程,但只有一个进程可获得连接,造成“惊 群”,影响性能 (默认为on的)

QQ截图20180705150503

调试和定位问题

1、daemon on|off 是否以守护进程方式运行nignx,默认是守护进程方式 (所谓的守护进程就是前台执行还是后台执行;此命令必须放到全局配置的语句块里;默认是on的在后台执行的;)

daemon off ;   (在前台执行,多用于测试中按ctrl+c就可以关闭nginx服务了)

2、master_process on|off 是否以master/worker模型运行nginx;默认为on; 如果设为off 将不启动worker

3、error_log file [level] 错误日志文件及其级别;出于调试需要,可设定为debug;但debug仅在编译时 使用了“–with-debug”选项时才有效

QQ截图20180705151427

 http协议的相关配置

# vim /etc/nginx/nginx.conf
 {
    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  /var/log/nginx/access.log  main;
    sendfile            on;
    tcp_nopush          on;
    tcp_nodelay         on;
    keepalive_timeout   65;
    types_hash_max_size 2048;
    include             /etc/nginx/mime.types;
    default_type        application/octet-stream;
}

由于在此修改会造成主配置文件的混乱;http服务的设置可以在自定义的配置文件里:/etc/nginx/conf.d/*.conf  里就行了。

配置一个虚拟主机  (基于主机头hostname)

QQ截图20180705153129

1)自建配置文件,参照上述模式来配置搭建三个虚拟主机的各自的配置文件

# vim /etc/nginx/conf.d/test.conf
server {
listen 80;
server_name www.a.com;
root /data/test1;
}

server {
listen 8080;
server_name www.b.com;
root /data/test2;
}

server {
listen 80;
server_name www.c.com;
root /data/test3;
}

2)建立三个主机各自的主页面文件

mkdir /data/test1
mkdir /data/test2
mkdir /data/test3
echo web1>/data/test1/index.html echo web2 >/data/test2/index.html echo web3 >/data/test3/index.html

3)重新加载nginx服务

#nginx -s reload

4)在另一台主机上访问:由于涉及到dns解析的问题可以临时在客户端将下面命令写到里面

#vim /etc/hosts
192.168.130.10(此为nginx服务器的IP地址) www.a.com  www.b.com   www.c.com
#curl www.a.com
web1
#curl www.b.com
web2
#curl c.com
web3

注:如果访问主机的IP:curl  192.168.130.10 此时会出现默认的本机的nginx服务的默认路径:因为前面主配置文件里写了:listen 80;default_server (为默认)如果取消此设置在访问则会按照配置文件的先后顺序来访问

default_server 设定为默认虚拟主机

ssl 限制仅能够通过ssl连接提供服务

backlog=number 超过并发连接数后,新请求进入后援队列的长度 (既访问数到达上限后,设置一个排队的数目,在后面排队)

rcvbuf=size 接收缓冲区大小

sndbuf=size 发送缓冲区大小

也可以实现基于以下方式来创建虚拟机

基于port; listen PORT; 指令监听在不同的端口

基于ip的虚拟主机 listen IP:PORT; IP 地址不同

4、server_name

虚拟主机的主机名称后可跟多个由空白字符分隔的字符串

支持*通配任意长度的任意字符 server_name *.magedu.com www.magedu.*

支持~起始的字符做正则表达式模式匹配,性能原因慎用 server_name ~^www\d+\.magedu\.com$

匹配优先级机制从高到低:

首先是字符串精确匹配 如:www.magedu.com
左侧*通配符 如:*.magedu.com
右侧*通配符 如:www.magedu.*
正则表达式 如: ~^.*\.magedu\.com$
default_server

5、tcp_nodelay on | off;

在keepalived模式下的连接是否启用TCP_NODELAY选项
当为off时,延迟发送,合并多个请求后一起发送 请求
默认On时,不延迟发送
可用于:http, server, location (在此语句块里添加)

6、sendfile on | off;

是否启用sendfile功能,在内核中封装报文直接发送
默认Off

7、server_tokens on | off | build | string

是否在响应报文的Server首部显示nginx版本 (默认是启用的)
server_tokens off    (此设置在主配置文件的http的语句块里添加)

8、root 定义路径相关的配置

设置web资源的路径映射;用于指明请求的URL所对应的文档的目录路径,可 用于http, server, location, if in location

示例:

定义路径:root          /data/www/vhost1;

http://www.magedu.com/images/logo.jpg (访问时输入的路径)

–> /data/www/vhosts/images/logo.jpg    (真实文件存放的路径)

本质:当访问//www.magedu.com/时真实的路径就是/data/www/vhost1;

9、location

在一个server中location配置段可存在多个,用于实现从uri到文件系统的路 径映射;ngnix会根据用户请求的URI来检查定义的所有location,并找出一个最 佳匹配,而后应用其配置 

示例:

server {
server_name www.magedu.com;
root     /data/www/
location      /images/ {
                           root       /app/test/;
}
}
当访问  http://www.magedu.com/images/> /app/test/images/     
但当访问http://www.magedu.com/时不添加子路径时又会访问/data/www/下的文件
location /images/ {
                root /app/test/;   (此种做法相当于重新指定了images子路径的真实文件存放的路径;
当用户去访问www. magedu.com/images时images目录下的真实问价被指定到了/app/test/; 里面) 使用此种方法可以将多个url的子路径指向不同的路径下: www.magedu.com/test1——->/data/test1/ www.magedu.com/news1——->/app/news1/ www.magedu.com/hello1——->/root/hello1/

总结:如果将location  / 定义为根的话当访问www.magedu.com/时会和系统默认的路径冲突;此时location的优先级比系统默认的根的优先级要高。

10、alias path; 路径别名,文档映射的另一种机制;仅能用于location上下文

location /bbs/ {
alias /web/forum/;

当访问www.magedu.com/bbs/时其真实访问的路径应该是 /web/forum/下的文件

11、index file …; 指定默认网页文件,注意:ngx_http_index_module模块

12、error_page (报错界面)

模块:ngx_http_core_module

可用位置:http, server, location, if in location

自定义错误界面:
#vim /etc/nginx/nginx.conf
server{
error_page  404   /404.html;
location   /404.html {
root    /data/error/;    #错误界面定义的路径
}
#mkdir -p /data/error
#cd /data/error #vim 404.html #新建的错误界面的文件名必须以此为文件名成,因为location /404.html已经定义了错误界面的名称 <h1>error</h1> error_page 404 =200 /404.html #将错误的404信息等于200的正确信息不会被浏览器劫持,看到的响应码为200,不是404了,
但看到的还是自定义的错误界面如下所示: # curl
-I www.a.com HTTP/1.1 200 OK Server: nginx/1.12.2 Date: Fri, 06 Jul 2018 13:47:45 GMT Content-Type: text/html Content-Length: 5 Last-Modified: Fri, 06 Jul 2018 12:34:22 GMT Connection: keep-alive ETag: "5b3f61ce-5" Accept-Ranges: bytes

13、try_files file … uri;

按顺序检查文件是否存在,返回第一个找到的文件或文件夹(结尾加斜线表示 为文件夹),如果所有的文件或文件夹都找不到,会进行一个内部重定向到最 后一个参数。只有最后一个参数可以引起一个内部重定向,之前的参数只设置 内部URI的指向。最后一个参数是回退URI且必须存在,否则会出现内部500错误

定义客户端请求的相关配置

1、keepalive_timeout timeout [header_timeout];  (长连接;一般情况下为了更多的用户访问可以考虑将长连接关上或者时间设置较短)

设定保持连接超时时长,0表示禁止长连接,默认为75s (如果是游戏业务则需要持续连接)

keepalive_timeout  0

2、keepalive_requests number;    然后就断开连接

在一次长连接上所允许请求的资源的最大数量, 默认为100 

3、keepalive_disable none | browser …

对哪种浏览器禁用长连接

4、send_timeout time;   (超过规定时间就断开连接)

向客户端发送响应报文的超时时长,此处是指两次写操作之间的间隔时长, 而非整个响应过程的传输时长

5、client_body_buffer_size size;

用于接收每个客户端请求报文的body部分的缓冲区大小;默认为16k;超 出此大小时,其将被暂存到磁盘上的由下面client_body_temp_path指令所定义 的位置 

6、client_body_temp_path path [level1 [level2 [level3]]];

设定存储客户端请求报文的body部分的临时存储路径及子目录结构和数量

目录名为16进制的数字; (对文件进行哈希值计算)

client_body_temp_path /var/tmp/client_body 1 2 2  (取哈希值的第一个第2,3个第4,5个创建文件夹)

1 1级目录占1位16进制,即2^4=16个目录 0-f

2 2级目录占2位16进制,即2^8=256个目录 00-ff

2 3级目录占2位16进制,即2^8=256个目录 00-ff

对客户端进行限制的相关配置

1、limit_rate rate;

限制响应给客户端的传输速率,单位是bytes/second 默认值0表示无限制

limit_rate 1048576(为1M的下载速度)是以字节为单位的

2、limit_except method … { … },仅用于location

限制客户端使用除了指定的请求方法之外的其它方法

method:GET, HEAD, POST, PUT, DELETE , MKCOL, COPY, MOVE, OPTIONS, PROPFIND, PROPPATCH, 
LOCK, UNLOCK, PATCH location limit_except GET { allow
192.168.1.0/24; deny all;
} 此代码用在location里面 除了GET和HEAD 之外其它方法仅允许192.
168.1.0/24网段主机使用 GET包含HEAD(看头部信息的)

文件操作优化的配置

1、aio on | off | threads[=pool];

是否启用aio功能 (系统默认是off的)

2、directio size | off;

directio 4m

当文件大于等于给定大小时,例如directio 4m,同步(直接)写磁盘,而非写缓存

directio off    (立即写磁盘而不写入缓存里)

3、open_file_cache off;

open_file_cache max=N [inactive=time];

nginx可以缓存以下三种信息:

 文件元数据:文件的描述符、文件大小和最近一次的修改时间
 打开的目录结构
 没有找到的或者没有权限访问的文件的相关信息

max=N:可缓存的缓存项上限;达到上限后会使用LRU算法实现管理(LRU算法:用的最少的淘汰算法)

inactive=time:缓存项的时间,如果超过此时间还没有人访问此缓存项就将其删除。

open_file_cache_min_uses指令所指定的次数的缓存项即为非活动项,将被删除

4、open_file_cache_errors on | off;

是否缓存查找时发生错误的文件一类的信息 默认值为off 

5、open_file_cache_min_uses number;

open_file_cache指令的inactive参数指定的时长内,至少被命中此处指定 的次数方可被归类为活动项

默认值为1 

6、open_file_cache_valid time;

缓存项有效性的检查频率 默认值为60s

ngx_http_access_module  (允许和拒绝访问的列表)

默认站点搭建起来是不限制用户访问的

规则:自上而下检查,一旦匹配,将生效,所以要将条件严格的置前

location / {
deny 192.168.1.1;  #拒绝此IP的访问
allow 192.168.1.0/24;   #允许此网段的访问
allow 10.1.1.0/16;         #允许此网段的访问
allow 2001:0db8::/32;   #支持IPV6地址段
deny all;       #拒绝所有的访问,即使自己访问自己也被拒绝
}

ngx_http_auth_basic_module (实现用户加密码访问)

cd   /etc/nginx/conf.d/
htpasswd -cm nginxuser httpuer1  #nginxuser:存放用户名及密码的文件;httpuer1:为创建的用户名
注:使用htppasswd命令需要安装httpd-tools包
htpasswd -cm nginxuser httpuer2   #创建第二个用户账号及密码

将生成的文件告诉配置文件路径:

此语句需要写在server{}语句块下。

QQ截图20180705210729

ngx_http_stub_status_module (可以检查服务器的运行状态)

用于输出nginx的基本状态信息

要启用的话需要将以下代码写进去:

location /status {
stub_status;
allow 172.16.0.0/16;    #允许那些主机可以看到本机的nginx的状态信息
deny all;   #剩余的全部都拒绝
}
在客户端访问:http://192.168.130.8/status/  #查看到访问的状态信息server accepts handled requests

1  1  1                    (访问之后可以发现如上的描述:为服务器的接收了几个;处理了几个;请求的有几个)

accepts:统计总值,已经接受的客户端请求的总数

handled:统计总值,已经处理完成的客户端请求的总数

requests:统计总值,客户端发来的总的请求数

Reading:当前状态,正在读取客户端请求报文首部的连接的连接数

Writing:当前状态,正在向客户端发送响应报文过程中的连接数

Waiting:当前状态,正在等待客户端发出请求的空闲连接数

ngx_http_log_module  (日志模块)

在主配置文件下的http语句块下写:

access_log off;   (关掉日志记录默认是开启的)

QQ截图20180707092853

上图中的时间格式可以更改为[$time_iso8601](此模式下月份也会显示成数字而不是英文字母了)

上述定义的变量可以在官网上的变量上查询具体的使用方法及参数。

对每个虚拟主机配置日志格式:(日志文件会自动生成的)

QQ截图20180707093656

ngx_http_gzip_module (压缩文件模块)

1、gzip on | off;

启用或禁用gzip压缩 

2、gzip_comp_level level;

压缩比由低到高:1 到 9 默认:1 

3、gzip_disable regex …;

匹配到客户端浏览器不执行压缩 

4、gzip_min_length length;

启用压缩功能的响应报文大小阈值

5、gzip_http_version 1.0 | 1.1;

设定启用压缩功能时,协议的最小版本 默认:1.1 

6、gzip_buffers number size;

支持实现压缩功能时缓冲区数量及每个缓存区的大小 默认:32 4k 或 16 8k 

7、gzip_types mime-type …;

指明仅对哪些类型的资源执行压缩操作;即压缩过滤器 默认包含有text/html,不用显示指定,否则出错

8、gzip_vary on | off;

如果启用压缩,是否在响应报文首部插入“Vary: Accept-Encoding”

ngx_http_ssl_module    (实现https的访问数据加密 )

1、ssl on | off; 为指定虚拟机启用HTTPS protocol, 建议用listen指令代替 (直接写成这样就可以了:listen 443 ssl; )

2、ssl_certificate file;

当前虚拟主机使用PEM格式的证书文件

3、ssl_certificate_key file;

当前虚拟主机上与其证书匹配的私钥文件

4、ssl_protocols [SSLv2] [SSLv3] [TLSv1] [TLSv1.1] [TLSv1.2];

支持ssl协议版本,默 认为后三个

5、ssl_session_cache off | none | [builtin[:size]] [shared:name:size];

none: 通知客户端支持ssl session cache,但实际不支持

builtin[:size]:使用OpenSSL内建缓存,为每worker进程私有

[shared:name:size]: 在多个worker进程之间共享一个缓存。(用的时候起个名并指定大小)

6、ssl_session_timeout time;

客户端连接可以复用ssl session cache中缓存的ssl参数的有效时长,默认5m (五分钟)

实例:

#cd /etc/pki/tls/certs/ (进入此文件夹下生成自签名的证书文件)
#make a.crt         #输入口令3编;开始自签名了输入;国家;省;市;公司;组织;
Country Name (2 letter code) [XX]:CN 
State or Province Name (full name) []:beijing
Locality Name (eg, city) [Default City]:beijing
Organization Name (eg, company) [Default Company Ltd]:magedu
Organizational Unit Name (eg, section) []:opt
Common Name (eg, your name or your server's hostname) []:www.a.com
Email Address []
#openssl rsa -in a.key -out aa.key   #将生成的私钥文件解密生成新的文件aa.key
#cp aa.key a.crt /etc/nginx/conf.d/   #将刚生成的两个文件复制到nginx目录下
#mv aa.key a.key   #改一下名称为了好看
# vim /etc/nginx/conf.d/test.conf
server {
listen 443 ssl;
server_name www.a.com;
root /data/test1;
ssl_certificate /etc/nginx/conf.d/a.crt;
ssl_certificate_key /etc/nginx/conf.d/a.key;
ssl_session_cache shared:sslcache:20m;
ssl_session_timeout 10m;
}
#nginx -s reload  #重新加载服务
# ss -ntl #查看端口
State Recv-Q Send-Q Local Address:Port Peer Address:Port 
LISTEN 0 128 *:80 *:* 
LISTEN 0 128 *:443 *:* 
#curl -k https://www.a.com   (-k 忽略证书检查访问)
https://192.168.60.4/  #在浏览器上也可以访问

在实际工作中只需将申请下来的两个证书文件放到指定的路径下就可以了。

对多个虚拟主机的不同网站实现不同的https加密。只需要执行上述相同的步骤就可以了,在各自的配置文件里写上自己的证书文件路径就可以了。(在apache上是不可以实现两个加密的虚拟主机两个网站https的)

ngx_http_rewrite_module (地址重定向模块)

last:重写完成后停止对当前URI在当前location中后续的其它重写操作, 而后对新的URI启动新一轮重写检查;提前重启新一轮循环,不建议在location中 使用

break:重写完成后停止对当前URI在当前location中后续的其它重写操作, 而后直接跳转至重写规则配置块之后的其它配置;结束循环,建议在location中使 用 

redirect:临时重定向,重写完成后以临时重定向方式直接返回重写后生成 的新URI给客户端,由客户端重新发起请求;使用相对路径,或者http://或https:// 开头,状态码:302

permanent:重写完成后以永久重定向方式直接返回重写后生成的新URI给 客户端,由客户端重新发起请求,状态码:301

注意:

如果在同一级配置块中存在多个rewrite规则,那么会自下而下逐个 检查;被某条件规则替换完成后,会重新一轮的替换检查

隐含有循环机制,但不超过10次;如果超过,提示500响应码,[flag]所表示 的标志位用于控制此循环机制

如果replacement是以http://或https://开头,则替换结果会直接以重向返 回给客户端, 即永久重定向301

示例:

location /bbs  {
             rewrite ^/bbs/(.*)$       /forum/$1     break;     ($1就是(.*)里的内容)

上条的意思就是:当用户访问根目录下的/bbs/下的(.*)内容时就会跳转到/forum/下的(.*)的内容

bbs和forum都在同一个目录下既在定义的root   /data/test1/(主页面目录下)

# vim /etc/nginx/conf.d/test.conf
server{
    listen 80 default_server;
    server_name www.a.com;
    root /data/test1/;
       location /bbs {
        rewrite ^/bbs/(.*)$ /forum/$1 break;
    }
}
#cd /data/test1
#mkdir bbs forum
#echo /forum/index.html > forum/index.html
#echo /bbs/index.html > bbs/index.html
#nginx -s reload #重新加载服务 # curl
-Li www.a.com/bbs/ #客户端测试 HTTP/1.1 200 OK Server: nginx/1.12.2 Date: Sun, 08 Jul 2018 08:56:56 GMT Content-Type: text/html Content-Length: 18 Last-Modified: Sat, 07 Jul 2018 11:19:16 GMT Connection: keep-alive ETag: "5b40a1b4-12" Accept-Ranges: bytes /forum/index.html

此时访问:www.a.com/bbs/    (应该是显示forum目录下的内容;bbs目录下可以没有任何内容,此目录也可以不存在,他只是url路径而已并且被重定向到forum目录下的内容了)

示例:当访问一个网站是不加密的时候跳转到加密的网站;背后只有一个虚拟主机网站

# vim /etc/nginx/conf.d/test.conf
server{
        listen 80 default_server;
        server_name www.a.com;
        root /data/test1/;
         ssl_certificate /etc/nginx/conf.d/a.crt;
         ssl_certificate_key /etc/nginx/conf.d/a.key;
         ssl_session_cache shared:sslcache:20m;
         ssl_session_timeout 10m;
          location / {
          if ( $scheme = http ) { #添加if判断语句
                rewrite / https://www.a.com/ redirect; #一般建议使用临时重定向
                }
        }
}
#nginx -s reload
# curl -Li www.a.com/
HTTP/1.1 302 Moved Temporarily
Server: nginx/1.12.2
Date: Sun, 08 Jul 2018 09:15:24 GMT
Content-Type: text/html
Content-Length: 161
Connection: keep-alive
Location: https://www.a.com/

curl: (7) Failed connect to www.a.com:443; Connection refused

示例:实现动静态页面的分离

当访问静态页面时(如,图片.文档)则跳转到一个路径下;当访问动态资源时(如;php程序)则跳转到另一个路径下:

QQ截图20180707143019

例如在;/data/test1/下新建一个pp.html的文件

curl  www.a.com/pp.txt   (就会显示pp.html文件里的内容)因为上面定义了只要访问(.*).txt 就会跳转到$1.html的文件里  其中$1=(.*)

ngx_http_referer_module  防盗链模块

QQ截图20180707151814

QQ截图20180707152128

如果不是从这几个地方访问的就给与拒绝;返回403;

ngx_http_proxy_module 反向代理模块

反向代理:转发请求至另一台主机

1、proxy_pass URL; proxy_pass后面路径不带uri时,会将location的uri传递(附加)给后端主机

#cd /data/test1
#mkdir admin
# vim /etc/nginx/conf.d/test.conf

server {
    listen 80;
    server_name www.a.com;
    location /admin {
        proxy_pass http://192.168.130.10/;  #带" / "
    }
}
访问http://www.a.com时相当于访问 http://192.168.130.10/
server {
    listen 80;
    server_name www.a.com;
    location /admin {
        proxy_pass http://192.168.130.10;  #不带" / "
    }
}
访问http://www.a.com时相当于访问 http://192.168.130.10/admin

如果location定义其uri时使用了正则表达式的模式,则proxy_pass之后必须不能使用uri; 用户请求时传递的uri将直接附加至后端服务器之后

2、proxy_set_header field value; 设定发往后端主机的请求报文的请求首部的值

proxy_set_header X-Real-IP  $remote_addr;  #$remote_addr客户端IP
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;  
#$proxy_add_x_forwarded_for代理IP

配合日志记录实现后端web服务器记录真正的客户端地址:

nginx代理主机:192.168.130.10
[root@nginx ~]# vim /etc/nginx/conf.d/test.conf
server {
    listen 80 default_server;
    server_name www.a.com;
    location / {
        proxy_pass http://192.168.130.11/;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
}
后台web服务:192.168.130.11
[root@nginx-1 ~]# vim /etc/nginx/nginx.conf
listen       80;
listen       [::]:80;
log_format  mylogformat  '$http_x_forwarded_for - $remote_user [$time_iso8601] "$request" '
                  '$status $body_bytes_sent "$http_referer" '
                  '"$http_user_agent" "$http_x_forwarded_for"';
[root@nginx-1 ~]# vim /etc/nginx/conf.d/vhosts.conf
server {
    listen 80 default_server;
    server_name www.a.com;
    root /data/test;
    access_log /var/log/nginx/www.a.com-access.log mylogformat;
}
root@nginx-1 ~]# mkdir -pv /data/test/
[root@nginx-1 ~]# echo www.a.com test page on nginx-1 > /data/test/index.html
客户端访问:192.168.130.8
[root@nginx-2 ~]# curl www.a.com
www.a.com test page on nginx-1
[root@nginx-1 ~]# tail -f /var/log/nginx/www.aa.com-access.log
192.168.130.8 - - [2018-07-08T10:07:35+00:00] "HEAD / HTTP/1.0" 200 0 "-""curl/7.29.0" "192.168.130.8"  #显示的是真正的客户端的IP地址

3、proxy_cache_path; 定义可用于proxy功能的缓存,在http中定义

proxy_cache_path path [levels=levels] [use_temp_path=on|off] keys_zone=name:size
[inactive=time] [max_size=size] [manager_files=number] [manager_sleep=time]
[manager_threshold=time] [loader_files=number] [loader_sleep=time]
[loader_threshold=time] [purger=on|off] [purger_files=number] [purger_sleep=time]
[purger_threshold=time];

配置代理缓存示例:在http配置定义缓存信息

[root@nginx ~]# vim /etc/nginx/nginx.conf
proxy_cache_path /var/cache/nginx/proxy_cache levels=1:1:1 
keys_zone=proxycache:20m #proxycache:20m 指内存中缓存的大小,主要用于存放key和metadata
inactive=120s max_size=1g; #max_size=1g 指磁盘存入文件内容的缓存空间最大值 [root@nginx ~]# mkdir /var/cache/nginx/
[root@nginx ~]# vim /etc/nginx/conf.d/vhosts.conf
server {
    listen 80 default_server;
    server_name www.a.com;
    location / {
        proxy_pass http://192.168.130.11/;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_cache proxycache;
        proxy_cache_key $request_uri;
        proxy_cache_valid 200 302 301 1h;
        proxy_cache_valid any 1m;
    }
}
[root@nginx-2 ~]# curl www.a.com
www.a.com test page on nginx-1
[root@nginx ~]# tree /var/cache/nginx/proxy_cache/
/var/cache/nginx/proxy_cache/
└── 9
    └── d
        └── 7
            └── 6666cd76f96956469e7be39d750cc7d9

4、proxy_cache zone|off; 默认off ,指明调用的缓存,或关闭缓存机制

5、proxy_cache_key string; 缓存中用于“键”的内容

默认值:proxy_cache_key $scheme$proxy_host$request_uri;

6、proxy_cache_valid [code ...] time; 定义对特定响应码的响应内容的缓存时长,定义在http{...}中

7、proxy_cache_use_stale; 在被代理的后端服务器出现哪种情况下,可以真接使用过期的缓存响应客户端

proxy_cache_use_stale error | timeout | invalid_header | updating | http_500 | http_502 
| http_503 | http_504 | http_403 | http_404 | off ...

8、proxy_cache_methods GET | HEAD | POST ...; 对哪些客户端请求方法对应的响应进行缓存,GET和HEAD方法总是被缓存

9、proxy_hide_header field; 默认nginx在响应报文不传递后端服务器的首部字段Date, Server, X-Pad, X-Accel-等,用于隐藏后端服务器特定的响应首部

10、proxy_connect_timeout time; 定义与后端服务器建立连接的超时时长,如超时会出现502错误,默认为60s,一般不建议超出75s

11、proxy_send_timeout time; 将请求发送给后端服务器的超时时长;默认为60s

12、proxy_read_timeout time; 等待后端服务器发送响应报文的超时时长,默认为60s

ngx_http_headers_module 模块

向由代理服务器响应给客户端的响应报文添加自定义首部,或修改指定首部的值

1、add_header name value [always]; 添加自定义首部

add_header X-Via  $server_addr;
add_header X-Cache $upstream_cache_status;
add_header X-Accel $server_name;

2、add_trailer name value [always]; 添加自定义响应信息的尾部

ngx_http_fastcgi_module 模块

转发请求到FastCGI服务器,不支持php模块方式

1、fastcgi_pass address; address为后端的fastcgi server的地址;可用位置:location, if in location

2、fastcgi_index name; fastcgi默认的主页资源;fastcgi_index index.php;

3、fastcgi_param parameter value [if_not_empty]; 设置传递给 FastCGI服务器的参数值,可以是文本,变量或组合

4、fastcgi_cache_path path ... 定义fastcgi的缓存:

fastcgi_cache_path path [levels=levels] [use_temp_path=on|off] 
keys_zone=name:size [inactive=time] [max_size=size] [manager_files=number]
[manager_sleep=time] [manager_threshold=time] [loader_files=number] [loader_sleep=time] [loader_threshold=time][purger=on|off] [purger_files=number] [purger_sleep=time] [purger_threshold=time];

path:缓存位置为磁盘上的文件系统
max_size=size:磁盘path路径中用于缓存数据的缓存空间上限
levels=levels:缓存目录的层级数量,以及每一级的目录数量
levels=ONE:TWO:THREE:示例:leves=1:2:2
keys_zone=name:size:k/v映射的内存空间的名称及大小
inactive=time:非活动时长

5、fastcgi_cache zone|off; 调用指定的缓存空间来缓存数据,可用位置:http, server, location

6、fastcgi_cache_key string; 定义用作缓存项的key的字符串,示例:fastcgi_cache_key $request_rui;

7、fastcgi_cache_methods GET | HEAD | POST ...; 为哪些请求方法使用缓存

8、fastcgi_cache_min_uses number; 缓存空间中的缓存项在inactive定义的非活动时间内至少要被访问到此处所指定的次数方可被认作活动项

9、fastcgi_keep_conn on | off; 收到后端服务器响应后,fastcgi服务器是否关闭连接,建议启用长连接

10、fastcgi_cache_valid [code ...] time; 不同的响应码各自的缓存时长

示例:配置 lnmp

1)在php

#yum install php-fpm php-mysql 
#vim /etc/php-fpm.d/www.conf
listen = 9000 #端口监听改为9000
listen.allowed_clients = 192.168.130.10 #允许nginx主机访问
#systemctl start php-fpm 
#mkdir -p /data/php #新建目录来存放php程序的主页面
创建连接数据库的测试代码:
vim /data/php/test.php
<?php
$dsn=’mysql:host=192.168.130.11;dbname=test’;
$username=’test’;
$passwd=’centos’;
$dbh=new
PDO($dsn,$username,$passwd);
var_dump($dbh);
?>

2)在nginx服务上

#yum install nginx
#vim /etc/nginx/conf.d/test1.conf
server{
listen 80 default_server;
server_name www.a.com;
root /data/test1/;
location ~ \.php$ {
fastcgi_pass 192.168.130.7:9000; #指定php服务器的的IP地址和端口号
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME /data/php$fastcgi_script_name; #指定php程序存放的路径;目录在php服务器上已创建
include fastcgi_params;                                                                                    
include fastcgi_params;
  }
}
#nginx -s reload

3)在数据库上

#yum install mariadb-server
#grant all on *.* to test@’192.168.130.%’ identified by ‘centos’; #在数据库中创建连接前端web服务器的用户账号

4)在客户端

curl 172.20.81.10/test.php

ngx_http_upstream_module 反向代理调度模块

用于将多个服务器定义成服务器组,而由proxy_pass, fastcgi_pass等指令进行引用,实现健康检查,负载均衡的功能

1、upstream name { ... } 定义后端服务器组,会引入一个新的上下文,默认调度算法是wrr,在http中定义

2、server address [parameters]; 在upstream上下文中server成员,以及相关的参数

address:

  • unix: /PATH/TO/SOME_SOCK_FILE socket文件
  • IP[:PORT] IP加端口
  • HOSTNAME[:PORT] 主机名加端口

parameters:

  • weight=number 权重,默认为1
  • max_conns 连接后端报务器最大并发活动连接数,1.11.5版本后支持
  • max_fails=number 失败尝试最大次数;超出此处指定的次数时,server将被标记为不可用,默认为1
  • fail_timeout=time 后端服务器标记为不可用状态的连接超时时长,默认10s
  • backup 将服务器标记为“备用”,即所有服务器均不可用时才启用
  • down 标记为“不可用”,配合ip_hash使用,实现灰度发布

3、ip_hash 源地址hash调度方法

4、least_conn 最少连接调度算法,当server拥有不同的权重时其为wlc,当所有后端主机连接数相同时,则使用wrr,适用于长连接

5、hash key [consistent]

基于指定的key的hash表来实现对请求的调度,此处的key可以直接文本、变量或二者组合

将请求分类,同一类请求将发往同一个upstream server,使用consistent参数,将使用ketama一致性hash算法,适用于后端是Cache服务器(如varnish)时使用

hash $request_uri consistent;
hash $remote_addr;

6、keepalive 连接数N:为每个worker进程保留的空闲的长连接数量,可节约nginx端口,并减少连接管理的消耗

7、health_check [parameters]; 健康状态检测机制;只能用于location上下文,仅对nginx plus有效

  • interval=time检测的频率,默认为5秒
  • fails=number:判定服务器不可用的失败检测次数;默认为1次
  • passes=number:判定服务器可用的失败检测次数;默认为1次
  • uri=uri:做健康状态检测测试的目标uri;默认为/
  • match=NAME:健康状态检测的结果评估调用此处指定的match配置块

8、match name { ... } 对backend server做健康状态检测时,定义其结果判断机制;只能用于http上下文,仅对nginx plus有效

  • status code[ code ...]: 期望的响应状态码
  • header HEADER[operator value]:期望存在响应首部,也可对期望的响应首部的值基于比较操作符和值进行比较
  • body:期望响应报文的主体部分应该有的内容

示例:实现反向代理的负载均衡功能

 

web1:

[root@web1 ~]# yum install httpd -y
[root@web1 ~]# echo web1 test page. > /var/www/html/index.html
[root@web1 ~]# vim /etc/httpd/conf/httpd.conf
LogFormat "%{client_ip}i %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
[root@web1 ~]# systemctl start httpd
[root@web1 ~]# systemctl enable httpd

web2:

[root@web2 ~]# yum install httpd -y
[root@web2 ~]# echo web2 test page. > /var/www/html/index.html
[root@web2 ~]# vim /etc/httpd/conf/httpd.conf
LogFormat "%{client_ip}i %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
[root@web2 ~]# systemctl start httpd
[root@web2 ~]# systemctl enable httpd

proxy:

[root@proxy ~]# curl http://192.168.130.10/ 
web1 test page.
[root@proxy ~]# curl http://192.168.130.11/
web2 test page.
[root@proxy ~]# yum install nginx -y
[root@proxy ~]# vim /etc/nginx/conf.d/test.conf  #在http和server中加入以下内容
http {
    upstream web {
        least_conn;
        server 192.168.130.10:80;
        server 192.168.130.11:80 weight=3;
    }
    proxy_cache_path /var/cache/nginx/proxy_cache
                     levels=1:1:1
                     keys_zone=proxycache:20m
                     inactive=120s
                     max_size=1g;
    server {
        location / {
            proxy_pass http://web;
            proxy_set_header client_ip $proxy_add_x_forwarded_for;
            proxy_cache proxycache;
            proxy_cache_key $request_uri;
            proxy_cache_valid 200 302 301 1h;
            proxy_cache_valid any 1m;
    }
}
[root@proxy ~]# mkdir /var/cache/nginx/
[root@proxy ~]# nginx
访问:http://192.168.130.8/

 

posted @ 2018-07-09 21:25  琼兔  阅读(735)  评论(0编辑  收藏  举报