Nginx

1. Nginx简介

Nginx(发音同engine x)是一款轻量级的Web服务器/反向代理服务器及电子邮件(IMAP/POP3)代理服务器,并在一个BSD-like协议下发行。
Nginx由俄罗斯的程序设计师Igor Sysoev所开发,最初供俄国大型的入口网站及搜寻引擎Rambler使用。
第一个公开版本0.1.0发布于2004年10月4日。其将源代码以类BSD许可证的形式发布,因它的稳定性、丰富的功能集、示例配置文件和低系统资源的消耗而闻名。2011年6月1日,Nginx 1.0.4发布。
Nginx的特点是占有内存少,并发能力强,事实上Nginx的并发能力确实在同类型的网页服务器中表现较好,中国大陆使用nginx网站用户有:百度、京东、新浪、网易、腾讯、淘宝等。

2. Nginx的特性与优点

2.1 Nginx的特性

Nginx是一个很牛的高性能Web和反向代理服务器,它具有很多非常优越的特性:
   ★在高连接并发的情况下,nginx是Apache服务器不错的替代品,能够支持高达50000个并发连接数的响应
   ★使用epoll and kqueue作为开发模型
   ★Nginx作为负载均衡服务器:Nginx既可在内部直接支持和PHP程序对外进行服务,也可支持作为HTTP代理服务器对外进行服务
   ★nginx采用C进行编写,不论系统资源开销还是CPU使用效率都比Perlbal要好很多

2.2 Nginx的优点

优点:
   ★高并发连接:官方测试能够支撑5万并发连接,在实际生产环境中跑到2-3万并发连接数
   ★内存消耗少:在3万并发连接下,开启的10个Nginx进程才消耗150M内存(15M*10=150M)
   ★配置文件非常简单:风格跟程序一样通俗易懂
   ★成本低廉:nginx为开源软件,可以免费使用。而购买F5 BIG-IP、NetScaler等硬件负载均衡交换机则需要十多万至几十万人民币
   ★支持Rewrite重写规则:能够根据域名、URL的不同,将HTTP请求分到不同的后端服务器群组
   ★内置的健康检查功能:如果Nginx Proxy后端的某台Web服务器宕机了,不会影响前端访问
   ★节省带宽:支持GZIP压缩,可以添加浏览器本地缓存的Header头
   ★稳定性高:用于反向代理,宕机的概率微乎其微
   ★模块化设计:模块可以动态编译
   ★外围支持好:文档全,二次开发和模块较多
   ★支持热部署:可以不停机重载配置文件
   ★支持事件驱动、AIO(AsyncIO,异步IO)、
   mmap(Memory Map,内存映射)等性能优化

3. Nginx的功能

3.1 Nginx的基本功能

  1. 静态资源的web服务器,能缓存打开的文件描述符
  2. http、smtp、pop3协议的反向代理服务器
  3. 缓存加速、负载均衡
  4. 支持FastCGI(fpm,LNMP),uWSGI(Python)等
  5. 模块化(非DSO机制),过滤器zip、SSI及图像的大小调整
  6. 支持SSL

3.2 Nginx的扩展功能

  1. 基于名称和IP的虚拟主机
  2. 支持keepalive
  3. 支持平滑升级
  4. 定制访问日志、支持使用日志缓冲区提高日志存储性能
  5. 支持URL重写
  6. 支持路径别名
  7. 支持基于IP及用户的访问控制
  8. 支持速率限制,支持并发数限制

4. Nginx的应用类别

  1. 使用Nginx结合FastCGI运行PHP、JSP、Perl等程序
  2. 使用Nginx作反向代理、负载均衡、规则过滤
  3. 使用Nginx运行静态HTML网页、图片
  4. Nginx与其他新技术的结合应用

5. Nginx的模块与工作原理

Nginx由内核和模块组成。其中,内核的设计非常微小和简洁,完成的工作也非常简单,仅仅通过查找配置文件将客户端请求映射到一个location block(location是nginx配置中的一个指令,用于URL匹配),而在这个location中所配置的每个指令将会启动不同的模块去完成相应的工作。

5.1 Nginx的模块分类

Nginx的模块从结构上分为核心模块、基础模块和第三方模块
   ★HTTP模块、EVENT模块和MAIL模块等属于核心模块
   ★HTTP Access模块、HTTP FastCGI模块、HTTP Proxy模块和HTTP Rewrite模块属于基本模块
   ★HTTP Upstream模块、Request Hash模块、Notice模块和HTTP Access Key模块属于第三方模块

用户根据自己的需要开发的模块都属于第三方模块。正是有了如此多模块的支撑,Nginx的功能才会如此强大

Nginx模块从功能上分为三类,分别是:
  ★Handlers(处理器模块)。此类模块直接处理请求,并进行输出内容和修改headers信息等操作。handlers处理器模块一般只能有一个
  ★Filters(过滤器模块)。此类模块主要对其他处理器模块输出的内容进行修改操作,最后由Nginx输出
  ★Proxies(代理器模块)。就是Nginx的HTTP Upstream之类的模块,这些模块主要与后端一些服务比如fastcgi等操作交互,实现服务代理和负载均衡等功能
  
Nginx模块分为:核心模块、事件模块、标准Http模块、可选Http模块、邮件模块、第三方模块和补丁等

Nginx基本模块:所谓基本模块,指的是Nginx默认的功能模块,它们提供的指令,允许你使用定义nginx基本功能的变量,在编译时不能被禁用,包括:
   ★核心模块:基本功能和指令,如进程管理和安全。常见
  的核心模块指令,大部分是放置在配置文件的顶部
   ★事件模块:在Nginx内配置网络使用的能力。常见的
   events(事件)模块指令,大部分是放置在配置文件的顶
   部
   ★配置模块:提供包含机制

6. Nginx的工作原理

  1. Nginx的模块直接被编译进nginx,因此属于静态编译方式。
  2. 启动nginx后,Nginx的模块被自动加载,与Apache不一样,首先将模块编译为一个so文件,然后在配置文件中指定是否进行加载。
  3. 在解析配置文件时,Nginx的每个模块都有可能去处理某个请求,但是同一个处理请求只能由一个模块来完成。

6.1 Nginx的进程架构:

启动Nginx时,会启动一个Master进程,这个进程不处理任何客户端的请求,主要用来产生worker线程,一个worker线程用来处理n个request。

在这里插入图片描述

6.2下图展示了Nginx模块一次常规的HTTP请求和响应的过程

在这里插入图片描述

6.3 下图展示了基本的WEB服务请求步骤

在这里插入图片描述

7. nginx的安装与配置

7.1 创建系统用户Nginx

[root@WangJiayue-4 ~]# useradd -r -M -s /sbin/nologin nginx

7.2 安装依赖环境

[root@WangJiayue-4 ~]# yum -y install pcre-devel openssl openssl-devel gd-devel gcc gcc-c++ epel-release
//省略安装过程
[root@WangJiayue-4 ~]# yum -y groups mark install 'Development Tools'
Loaded plugins: fastestmirror
There is no installed groups file.
Maybe run: yum groups mark convert (see man yum)
Loading mirror speeds from cached hostfile
epel/x86_64/metalink                                                                                                                               | 6.5 kB  00:00:00     
 * base: mirrors.nju.edu.cn
 * epel: mirrors.bfsu.edu.cn
 * extras: mirrors.nju.edu.cn
 * updates: mirrors.nju.edu.cn
epel                                                                                                                                               | 4.7 kB  00:00:00     
(1/3): epel/x86_64/group_gz                                                                                                                        |  95 kB  00:00:00     
(2/3): epel/x86_64/updateinfo                                                                                                                      | 1.0 MB  00:00:01     
(3/3): epel/x86_64/primary_db                                                                                                                      | 6.9 MB  00:02:47     
Marked install: Development Tools
[root@WangJiayue-4 ~]# 

7.3 创建日志存放目录

[root@WangJiayue-4 ~]#  mkdir -p /var/log/nginx
[root@WangJiayue-4 ~]#  chown -R nginx.nginx /var/log/nginx

7.4 下载解压并安装Nginx

[root@WangJiayue-4 ~]# cd /usr/src/
[root@WangJiayue-4 src]# wget http://nginx.org/download/nginx-1.18.0.tar.gz
//省略下载过程
[root@WangJiayue-4 src]# tar xf nginx-1.18.0.tar.gz 
[root@WangJiayue-4 src]# cd nginx-1.18.0/
[root@WangJiayue-4 nginx-1.18.0]# ./configure \
> --prefix=/usr/local/nginx \
> --user=nginx \
> --group=nginx \
> --with-debug \
> --with-http_ssl_module \
> --with-http_realip_module \
> --with-http_image_filter_module \
> --with-http_gunzip_module \
> --with-http_gzip_static_module \
> --with-http_stub_status_module \
> --http-log-path=/var/log/nginx/access.log \
> --error-log-path=/var/log/nginx/error.log
//省略过程
[root@WangJiayue-4 nginx-1.18.0]# make -j $(grep 'processor' /proc/cpuinfo | wc -l) && make install
//省略过程

7.5 安装后配置

[root@WangJiayue-4 ~]# echo 'export PATH=/usr/local/nginx/sbin:$PATH' > /etc/profile.d/nginx.sh
[root@WangJiayue-4 ~]# source /etc/profile.d/nginx.sh 

//服务控制方式,使用Nginx命令
    -t  //检查配置文件语法
    -v  //输出nginx的版本
    -c  //指定配置文件的路径
    -s  //发送服务控制信号,可选值有{stop|quit|reopen|reload}

[root@WangJiayue-4 ~]# nginx      //启动Nginx
[root@WangJiayue-4 ~]# ss -antl
State      Recv-Q Send-Q                                        Local Address:Port                                                       Peer Address:Port              
LISTEN     0      128                                                       *:80                                                                    *:*                  
LISTEN     0      128                                                       *:22                                                                    *:*                  
LISTEN     0      100                                               127.0.0.1:25                                                                    *:*                  
LISTEN     0      128                                                      :::22                                                                   :::*                  
LISTEN     0      100                                                     ::1:25                                                                   :::*                  

8. Nginx的配置文件详解

主配置文件:/usr/local/nginx/conf/nginx.conf
   ★默认启动nginx时,使用的配置文件是:
   安装路径/conf/nginx.conf文件
   ★可以在启动nginx时通过-c选项来指定要读取的配置文
   件nginx常见的配置文件及其作用

8.1 Nginx常见的配置文件及其作用

配置文件作用
nginx.confNginx的基本配置文件
mime.typesMIME类型关联的扩展文件
fastcgi.conf与fastcgi相关的配置
proxy.conf与proxy相关的配置
sites.conf配置nginx提供的网站,包括虚拟主机

8.2 nginx.conf配置详解

nginx.conf的内容分为以下几段: 
  ★main配置段:全局配置段。其中main配置段中可能包
  含event配置段
   ★event {}:定义event模型工作特性
   ★http {}:定义http协议相关的配

置配置指令:要以分号结尾,语法格式如下:
derective value1 [value2 …];

支持使用变量:
  ★内置变量:模块会提供内建变量定义
  ★自定义变量:set var_name value

用于调试、定位问题的配置参数 
   ★daemon {on|off}; //是否以守护进程方式运行nginx,调试时应设置为off
   ★master_process {on|off}; //是否以master/worker模型来运行nginx,调试时可以设置为off
   ★error_log 位置 级别; //配置错误日志

error_log里的位置和级别能有以下可选项:

位置级别
file
stderr
syslog:server=address[,parameter=value]
memory:size
debug:若要使用debug级别,需要在编译nginx时使用–with-
debug选项
info
notice
warn
error
crit
alert
emerg

8.3 正常运行必备的配置参数

★user USERNAME [GROUPNAME]; //指定运行worker进程的用户和组
   ★pid /path/to/pid_file; //指定nginx守护进程的pid文件
   ★worker_rlimit_nofile number; //设置所有worker进程最
   大可以打开的文件数,默认为1024
   ★worker_rlimit_core size; //指明所有worker进程所能够
   使用的总体的最大核心文件大小,保持默认即可

8.4 优化性能的配置参数

worker_processes n;    //启动n个worker进程,这里的n为了避免上下文切换,通常设置为cpu总核心数-1或等于总核心数
worker_cpu_affinity cpumask ...;    //将进程绑定到某cpu中,避免频繁刷新缓存
//cpumask:使用8位二进制表示cpu核心,如:
    0000 0001   //第一颗cpu核心
    0000 0010   //第二颗cpu核心
    0000 0100   //第三颗cpu核心
    0000 1000   //第四颗cpu核心
    0001 0000   //第五颗cpu核心
    0010 0000   //第六颗cpu核心
    0100 0000   //第七颗cpu核心
    1000 0000   //第八颗cpu核心
timer_resolution interval;    //计时器解析度。降低此值,可减少gettimeofday()系统调用的次数
worker_priority number;    //指明worker进程的nice值

8.5 事件相关的配置:event{}段中的配置参数

accept_mutex {off|on};    //master调度用户请求至各worker进程时使用的负载均衡锁;on表示能让多个worker轮流地、序列化地去响应新请求
lock_file file;    //accept_mutex用到的互斥锁锁文件路径
use [epoll | rtsig | select | poll];    //指明使用的事件模型,建议让nginx自行选择
worker_connections #;    //每个进程能够接受的最大连接数

8.6 网络连接相关的配置参数

keepalive_timeout number;    //长连接的超时时长,默认为65s
keepalive_requests number;    //在一个长连接上所能够允许请求的最大资源数
keepalive_disable [msie6|safari|none];    //为指定类型的UserAgent禁用长连接
tcp_nodelay on|off;    //是否对长连接使用TCP_NODELAY选项,为了提升用户体验,通常设为on
client_header_timeout number;    //读取http请求报文首部的超时时长
client_body_timeout number;    //读取http请求报文body部分的超时时长
send_timeout number;    //发送响应报文的超时时长

8.7 fastcgi的相关配置参数

LNMP:php要启用fpm模型
配置示例如下:

location ~ \.php$ {
  root html;
  fastcgi_pass 127.0.0.1:9000;      //定义反向代理
  fastcgi_index index.php;
  fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;
  include fastcgi_params;
}

8.8 常需要进行调整的参数

worker_processes
worker_connections
worker_cpu_affinity
worker_priority

8.9 Nginx作为web服务器时使用的配置:http{}段的配置参数

http{...}:配置http相关,由ngx_http_core_module模块引入。nginx的HTTP配置主要包括四个区块,结构如下:

http {//协议级别
  include mime.types;
  default_type application/octet-stream;
  keepalive_timeout 65;
  gzip on;
  upstream {//负载均衡配置
    ...
  }
  server {//服务器级别,每个server类似于httpd中的一个<VirtualHost>
    listen 80;
    server_name localhost;
    location / {//请求级别,类似于httpd中的<Location>,用于定义URL与本地文件系统的映射关系
      root html;
      index index.html index.htm;
    }
  }
}

http{}段配置指令:
server {}:定义一个虚拟主机,示例如下:

server {
  listen 80;
  server_name www.idfsoft.com;
  root "/vhosts/web";
}

listen:指定监听的地址和端口

listen address[:port];
listen port;

server_name NAME […]; 后面可跟多个主机,名称可使用正则表达式或通配符

当有多个server时,匹配顺序如下:

  1. 先做精确匹配检查
  2. 左侧通配符匹配检查,如*.idfsoft.com
  3. 右侧通配符匹配检查,如mail.*
  4. 正则表达式匹配检查,如~ ^.*.idfsoft.com$
  5. default_server

root path; 设置资源路径映射,用于指明请求的URL所对应的资源所在的文件系统上的起始路径
alias path; 用于location配置段,定义路径别名
index file; 默认主页面

index index.php index.html;

error_page code […] [=code] URI | @name 根据http响应状态码来指明特用的错误页面,例如 error_page 404 /404_customed.html

[=code]:以指定的响应码进行响应,而不是默认的原来的响应,默认表示以新资源的响应码为其响应码,例如 error_page 404 =200 /404_customed.html

log_format 定义日志格式

og_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;

//注意:此处可用变量为nginx各模块内建变量

location区段,通过指定模式来与客户端请求的URI相匹配

//功能:允许根据用户请求的URI来匹配定义的各location,匹配到时,此请求将被相应的location配置块中的配置所处理,例如做访问控制等功能

//语法:location [ 修饰符 ] pattern {......}

//在配置文件添加一个web信息
location /zabbix {
            root   /opt/myweb;    //URI = root + location + index
            index  index.html;
        }

安装nginx-echo模块

//下载并解压模块
[root@WangJiayue-4 src]# wget https://github.com/openresty/echo-nginx-module/archive/v0.61.tar.gz
    //省略下载过程
[root@WangJiayue-4 src]# tar xf v0.61.tar.gz
//重新编译nginx
[root@WangJiayue-4 ~]# cd /usr/src/nginx-1.18.0/
[root@WangJiayue-4 nginx-1.18.0]# ./configure --prefix=/usr/local/nginx --user=nginx --group=nginx --with-debug --with-http_ssl_module --with-http_realip_module --with-http_image_filter_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_stub_status_module --http-log-path=/var/log/nginx/access.log --error-log-path=/var/log/nginx/error.log --add-module=/root/echo-nginx-module-0.61
    //在最后添加  `--add-module=/root/echo-nginx-module-0.61`
[root@WangJiayue-4 nginx-1.18.0]# make

//备份
[root@WangJiayue-4 nginx-1.18.0]# mv /usr/local/nginx/sbin/nginx /opt
[root@WangJiayue-4 nginx-1.18.0]# cp /usr/src/nginx-1.18.0/objs/nginx /usr/local/nginx/sbin/

//重读配置文件
[root@WangJiayue-4 ~]# nginx -s reload

常用修饰符说明:

修饰符功能
=精确匹配
~正则表达式模式匹配,区分大小写
~*正则表达式模式匹配,不区分大小写
^~前缀匹配,类似于无修饰符的行为,也是以指定模块开始,不同的是,如果模式匹配,那么就停止搜索其他模式了,不支持正则表达式
@定义命名location区段,这些区段客户端不能访问,只可以由内部产生的请求来访问,如try_files或error_page等

没有修饰符表示必须以指定模式开始,如:

server {
  server_name www.idfsoft.com;
  location /abc {
    ......
  }
}

没有修饰符表示任何location都可以匹配

[root@WangJiayue-4 ~]# vim /usr/local/nginx/conf/nginx.conf

location /abc {
            echo "没有修饰符";
        }
        
[root@WangJiayue-3 ~]# curl http://192.168.222.135/abc
没有修饰符
[root@WangJiayue-3 ~]# curl http://192.168.222.135/abc/
没有修饰符
[root@WangJiayue-3 ~]# curl http://192.168.222.135/abc?p1=11
没有修饰符

=:必须与指定的模式精确匹配

[root@WangJiayue-4 ~]# vim /usr/local/nginx/conf/nginx.conf
location = /abc {
	echo "精确匹配";
}

[root@WangJiayue-3 ~]# curl 192.168.222.135/abc
精确匹配
[root@WangJiayue-3 ~]# curl 192.168.222.135/abc?p1=11&p2=22
精确匹配
[root@WangJiayue-3 ~]# curl 192.168.222.135/abc/
<html>
<head><title>404 Not Found</title></head>
<body>
<center><h1>404 Not Found</h1></center>
<hr><center>nginx/1.18.0</center>
</body>
</html>

~:指定的正则表达式要区分大小写

[root@WangJiayue-4 ~]# vim /usr/local/nginx/conf/nginx.conf
location ~ ^/abc$ {
	echo "正则表达式,区分大小写";
}

[root@WangJiayue-3 ~]# curl 192.168.222.135/abc
正则表达式,区分大小写
[root@WangJiayue-3 ~]# curl 192.168.222.135/abc?p1=11&p2=22
正则表达式,区分大小写
[root@WangJiayue-3 ~]# curl 192.168.222.135/abc/
<html>
<head><title>404 Not Found</title></head>
<body>
<center><h1>404 Not Found</h1></center>
<hr><center>nginx/1.18.0</center>
</body>
</html>
[root@WangJiayue-3 ~]# curl 192.168.222.135/ABC
<html>
<head><title>404 Not Found</title></head>
<body>
<center><h1>404 Not Found</h1></center>
<hr><center>nginx/1.18.0</center>
</body>
</html>

~*:表示指定的正则表达式不区分大小写

[root@WangJiayue-4 ~]# vim /usr/local/nginx/conf/nginx.conf
location ~* ^/abc$ {
            echo "正则表达式,不区分大小写";
        }

[root@WangJiayue-3 ~]# curl 192.168.222.135/abc
正则表达式,不区分大小写
[root@WangJiayue-3 ~]# curl 192.168.222.135/abc?p1=11&p2=22
正则表达式,不区分大小写
[root@WangJiayue-3 ~]# curl 192.168.222.135/ABC
正则表达式,不区分大小写
[root@WangJiayue-3 ~]# curl 192.168.222.135/abc/
<html>
<head><title>404 Not Found</title></head>
<body>
<center><h1>404 Not Found</h1></center>
<hr><center>nginx/1.18.0</center>
</body>
</html>

~:类似于无修饰符的行为,也是以指定模式开始,不同的是,如果模式匹配,则停止搜索其他模式

8.10 查找顺序和优先级:由高到底依次为

带有=的精确匹配优先
正则表达式按照他们在配置文件中定义的顺序
带有^~修饰符的,开头匹配
带有或*修饰符的,如果正则表达式与URI匹配
没有修饰符的精确匹配

优先级:( location = 路径 ) --> ( location ^~ 路径 ) --> ( location ~ 正则 ) --> ( location ~* 正则 ) --> ( location 路径 )

8.11 访问控制

用于location段
allow:设定允许哪台或哪些主机访问,多个参数间用空格隔开
deny:设定禁止哪台或哪些主机访问,多个参数间用空格隔开

示例:

allow 192.168.1.1/32 172.16.0.0/16;
deny all;

9.基于用户认证

9.1 生成密码文件

[root@WangJiayue-4 ~]# yum -y install httpd-tools
//省略安装过程
[root@WangJiayue-4 ~]#  htpasswd -c -m /usr/local/nginx/conf/password admin
New password:                                  //输入自己的密码
Re-type new password:                      //重复一遍密码
Adding password for user admin
[root@WangJiayue-4 ~]# ls /usr/local/nginx/conf
fastcgi.conf          fastcgi_params          koi-utf  mime.types          nginx.conf          password     scgi_params.default  uwsgi_params.default
fastcgi.conf.default  fastcgi_params.default  koi-win  mime.types.default  nginx.conf.default  scgi_params  uwsgi_params         win-utf
[root@WangJiayue-4 ~]# cat /usr/local/nginx/conf/password
admin:$apr1$d7DLQZE9$3s9ZvnWbbvEgoJiSPkHwV/

9.2 修改配置文件

[root@WangJiayue-4 ~]# vim /usr/local/nginx/conf/nginx.conf

location /abc {
            root   html;
            index  index.html;
            auth_basic "hello";
            auth_basic_user_file /usr/local/nginx/conf/password;
        }

9.3 生成访问测试文件

[root@WangJiayue-4 html]# cd /usr/local/nginx/html
[root@WangJiayue-4 html]# mkdir abc
[root@WangJiayue-4 html]# echo 'abc test page' > abc/index.html
[root@WangJiayue-4 html]# ls
50x.html  abc  index.html
[root@WangJiayue-4 html]# ls abc/
index.html

在这里插入图片描述

10. 配置https

10.1 生成秘钥

//CA生成一对密钥
[root@WangJiayue-4 ~]# cd /etc/pki/CA 
[root@WangJiayue-4 CA]# ls
certs  crl  newcerts  private
[root@WangJiayue-4 CA]# (umask 077;openssl genrsa -out private/cakey.pem 2048)    //生成秘钥
Generating RSA private key, 2048 bit long modulus
.............................................+++
...............................+++
e is 65537 (0x10001)
[root@WangJiayue-4 CA]# openssl rsa -in private/cakey.pem -pubout         //提取公钥
writing RSA key  
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAn3BSJeY7LjMqR48e/dgN
pdFiBkB66hXchgRKqpV9/7+qH/UFmZ2U7PmIjJE8xdZ68posLiXI8CBNLJIlw35k
FWngIjRjLgagy2sg+BuoeZO4F5fVNgn4OruWVre4QGukMIkCC9WyK5cV1UlGIsJt
6nLTp82kVck2d4/IwSnlUbJm3vd8FtTLlOCs4+GHz1BadzCbj9Ir0UFonVN4hAWp
58ZhDOCWq95paqR+9ccuzudT7liyoX518vxPI68CVALhUu4Vw0F6mkNUJZnmEMq+
rQxCaPX/VC6jCtoF8/5hbbh5FJEX1ZkSsQEKAqmyw9rHbJUn9wRpOxpwt3PeTt72
rwIDAQAB
-----END PUBLIC KEY-----

//CA生成自签署证书
[root@WangJiayue-4 CA]# openssl req -new -x509 -key private/cakey.pem -out cacert.pem -days 365
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [XX]:CN
State or Province Name (full name) []:HB
Locality Name (eg, city) [Default City]:WH
Organization Name (eg, company) [Default Company Ltd]:www.wangjiayue.com
Organizational Unit Name (eg, section) []:www.wangjiayue.com
Common Name (eg, your name or your server's hostname) []:www.wangjiayue.com
Email Address []:XXXXXXX@qq.com   
[root@WangJiayue-4 CA]# openssl x509 -text -in cacert.pem   //读取证书内容,这里我们省略读取出来的内容
[root@WangJiayue-4 CA]# touch index.txt && echo 01 > serial
[root@WangJiayue-4 CA]# cd
[root@WangJiayue-4 ~]# 

//Nginx服务器生成秘钥
[root@WangJiayue-4 ~]# cd /usr/local/nginx
[root@WangJiayue-4 nginx]# mkdir ssl
[root@WangJiayue-4 nginx]# cd ssl/
[root@WangJiayue-4 ssl]# (umask 077;openssl genrsa -out nginx.key 2048)
Generating RSA private key, 2048 bit long modulus
..........................+++
...........+++
e is 65537 (0x10001)

//Nginx生成证书自签署请求
[root@WangJiayue-4 ssl]# openssl req -new -key nginx.key -days 365 -out nginx.csr
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [XX]:CN
State or Province Name (full name) []:HB
Locality Name (eg, city) [Default City]:WH
Organization Name (eg, company) [Default Company Ltd]:www.wangjiayue.com
Organizational Unit Name (eg, section) []:www.wangjiayue.com
Common Name (eg, your name or your server's hostname) []:www.wangjiayue.com
Email Address []:XXXXXXX@qq.com

Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:
An optional company name []:
[root@WangJiayue-4 ssl]# 

//CA签署nginx提交上来的证书
[root@WangJiayue-4 ssl]# openssl ca -in nginx.csr -out nginx.crt -days 365
Using configuration from /etc/pki/tls/openssl.cnf
Check that the request matches the signature
Signature ok
Certificate Details:
        Serial Number: 1 (0x1)
        Validity
            Not Before: Aug 11 17:07:15 2020 GMT
            Not After : Aug 11 17:07:15 2021 GMT
        Subject:
            countryName               = CN
            stateOrProvinceName       = HB
            organizationName          = www.wangjiayue.com
            organizationalUnitName    = www.wangjiayue.com
            commonName                = www.wangjiayue.com
            emailAddress              = XXXXXXX@qq.com
        X509v3 extensions:
            X509v3 Basic Constraints: 
                CA:FALSE
            Netscape Comment: 
                OpenSSL Generated Certificate
            X509v3 Subject Key Identifier: 
                60:7A:42:7C:45:33:9D:12:ED:6F:80:56:70:71:8D:9C:A8:47:C5:95
            X509v3 Authority Key Identifier: 
                keyid:BC:BC:F1:9C:B9:A2:A1:38:EC:DE:F4:67:7A:1C:46:E9:5C:AD:18:3B

Certificate is to be certified until Aug 11 17:07:15 2021 GMT (365 days)
Sign the certificate? [y/n]:y

1 out of 1 certificate requests certified, commit? [y/n]y
Write out database with 1 new entries
Data Base Updated
[root@WangJiayue-4 ssl]# 

10.2 修改配置文件

[root@WangJiayue-4 ~]# vim /usr/local/nginx/conf/nginx.conf

//把以下内容的注释取消掉并修改内容
 server {
        listen       443 ssl;
        server_name  www.wangjiayue.com;

        ssl_certificate      /usr/local/nginx/ssl/nginx.crt;
        ssl_certificate_key  /usr/local/nginx/ssl/nginx.key;

        ssl_session_cache    shared:SSL:1m;
        ssl_session_timeout  5m;

        ssl_ciphers  HIGH:!aNULL:!MD5;
        ssl_prefer_server_ciphers  on;

        location / {
            root   html;
            index  index.html index.htm;
        }
    }
    
[root@WangJiayue-4 ~]#nginx -s reload

在这里插入图片描述

11. 开启状态界面

开启status:
/usr/local/nginx/conf/nginx.conf配置文件中添加

location /status {
  stub_status {on | off};
  allow 192.168.222.139/24;     //服务端的IP
  deny all;
}

访问时输入192.168.222.139/status(这里也是 服务端的IP/status

状态码所表示含义
Active connections当前所有处于打开状态的连接数
accepts总共处理了多少个连接
handled成功创建多少握手
requests总共处理了多少个请求
ReadingNginx读取到客户端的Header信息数,表示正处于接收请求状态的连接数
WritingNginx返回给客户端的Header信息数,表示请求已经接收完成,且正处于处理请求或发送响应的过程中的连接数
Waiting开启keep-alive的情况下,这个值等于active - (reading + writing),意思就是Nginx已处理完正在等候下一次请求指令的驻留连接

状态页面信息详解:

在这里插入图片描述

12. rewrite

语法:rewrite regex replacement flag;

rewrite ^/images/(.*\.jpg)$ /imgs/$1 break;

此处的$1用于引用(.*.jpg)匹配到的内容)

rewrite ^/bbs/(.*)$ http://www.idfsoft.com/index.html redirect;

如上例所示,replacement可以是某个路径,也可以是某个URL(URL:资源在服务器上的唯一地址)

12.1 常见flag

flag作用
last基本上都用这个flag,表示当前的匹配结束,继续下一个匹配,最多匹配10个到20个一旦此rewrite规则重写完成后,就不再被后面其它rewrite规则进行处理而是由UserAgent重新对重写后的URL再一次发起请求,并从头开始执行类似的过程
break中止Rewrite,不再继续匹配一旦此rewrite规则重写完成后,UserAgent对新的URL重新发起请求,且不再会被当前location内的任何rewrite规则所检查
redirect以临时重定向的HTTP状态302返回新的URL
permanent以永久重定向的HTTP状态301返回新的URL

rewrite模块的作用是用来执行URL重定向。这个机制有利于去掉恶意访问的url,也有利于搜索引擎优化(SEO)

12.2 nginx使用的语法源于Perl兼容正则表达式(PCRE)库,基本语法

标识符意义
^必须以^后的实体开头
$必须以$前的实体结尾
.匹配任意字符
[]匹配指定字符集内的任意字符
[^]匹配任何不包括在指定字符集内的任意字符串
()分组,组成一组用于匹配的实体,通常会有

捕获子表达式,可以捕获放在()之间的任何文本,比如:

^(hello|sir)$       //字符串为“hi sir”捕获的结果:$1=hi$2=sir

这些被捕获的数据,在后面就可以当变量一样使用了

12.3 实例

//这里创建一个目录并放入一张图片进去

[root@WangJiayue html]# mkdir images
[root@WangJiayue html]# cd images/
[root@WangJiayue images]# ls
1.jpg
[root@WangJiayue images]# pwd
/usr/local/nginx/html/images

//然后在 /usr/local/nginx/conf/nginx.conf 配置文件中添加内容

[root@WangJiayue ~]# vim /usr/local/nginx/conf/nginx.conf

location /images {
            alias html/images;
        }
        
[root@WangJiayue ~]# 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@WangJiayue ~]# nginx -s reload

在这里插入图片描述

成功访问到图片

12.4 配置rewrite

//这里首先更改一下目录名称让用户不能访问到图片

[root@WangJiayue html]# mv images imgs
[root@WangJiayue html]# ls
50x.html imgs index.html  index.php  zabbix
[root@WangJiayue html]# cd imgs/
[root@WangJiayue imgs]# ls
1.jpg

在这里插入图片描述

//然后配置rewrite让用户用原有方式可以再次访问到图片

[root@WangJiayue html]# vim /usr/local/nginx/conf/nginx.conf
//要把老的配置注释或删掉
        
        location /images {
            rewrite ^/images/(.*\.jpg)$ /imgs/$1 break;
        }
        
[root@WangJiayue html]# nginx -s reload

在这里插入图片描述
配置完成后用原地址发现可以再次访问

除了可以跳转到指定目录外,也可以跳转到某个指定的地址

[root@WangJiayue html]# vim /usr/local/nginx/conf/nginx.conf

location /images {
            rewrite ^/images/(.*\.jpg)$ https://blog.csdn.net/wanfjiayue break;    //这里写的是我的博客地址
         }

[root@WangJiayue html]# nginx -s reload

在这里插入图片描述
输入完成后回车自动跳转到我的博客页面
在这里插入图片描述
演示last的使用

[root@WangJiayue html]# vim /usr/local/nginx/conf/nginx.conf

location /images {
            rewrite ^/images/(.*\.jpg)$ /imgs/$1 last;
        }
             
        location /imgs {
            rewrite ^/imgs/(.*\.jpg)$ https://blog.csdn.net/wanfjiayue last;
        }

[root@WangJiayue html]# nginx -s reload

在完成匹配1.jpg图片后会立马进行下一次匹配最终会访问到我的博客页面
在这里插入图片描述

13. if

语法:if (condition) {…}

应用场景:
  ★server段
  ★location段

13.1 常见的condition

常见的condition
   ★变量名(变量值为空串,或者以“0”开始,则为false,其它的均为true)
   ★以变量为操作数构成的比较表达式(可使用=,!=类似的比较操作符进行测试)
   ★正则表达式的模式匹配操作
      ☆ ~:区分大小写的模式匹配检查
      ☆ ~:不区分大小写的模式匹配检查
      ☆ !和!
:对上面两种测试取反
   ★测试指定路径为文件的可能性(-f,!-f)
   ★测试指定路径为目录的可能性(-d,!-d)
   ★测试文件的存在性(-e,!-e)
   ★检查文件是否有执行权限(-x,!-x)

14. 基于浏览器实现分离案例

[root@WangJiayue ~]# cd /usr/local/nginx/html/
[root@WangJiayue html]# mkdir  MSIE Google
[root@WangJiayue html]# echo 'This is Google page' > Google/index.html
[root@WangJiayue html]# echo 'This is IE test page.' > MSIE/index.html

[root@WangJiayue html]# vim /usr/local/nginx/conf/nginx.conf


        location html/ {

            if ($http_user_agent ~ MSIE) {
                rewrite ^(.*)$ /MSIE/$1 break;
        }

            if ($http_user_agent ~ Google) {
                rewrite ^(.*)$ /Google/$1 break;
        }
            root   html;
            index  index.html index.htm;
        }

        location /MSIE {
            root   html;
            index  index.html;
        }

        location /Google {
            root   html;
            index  index.html;
        }

[root@WangJiayue html]# nginx -s reload

Google浏览器访问
在这里插入图片描述
在这里插入图片描述

15. 防盗链案例

location ~* \.(jpg|gif|jpeg|png)$ {
  valid_referers none blocked www.idfsoft.com;
  if ($invalid_referer) {
    rewrite ^/ http://www.idfsoft.com/403.html;
  }
}

16. 反向代理与负载均衡

简介:

nginx通常被用作后端服务器的反向代理,这样就可以很方便的实现动静分离以及负载均衡,从而大大提高服务器的处理能力。
  nginx实现动静分离,其实就是在反向代理的时候,如果是静态资源,就直接从nginx发布的路径去读取,而不需要从后台服务器获取了。
  但是要注意,这种情况下需要保证后端跟前端的程序保持一致,可以使用Rsync做服务端自动同步或者使用NFS、MFS分布式共享存储。
  Http Proxy模块,功能很多,最常用的是proxy_pass和proxy_cache
  
  如果要使用proxy_cache,需要集成第三方的ngx_cache_purge模块,用来清除指定的URL缓存。这个集成需要在安装nginx的时候去做,如:
./configure --add-module=…/ngx_cache_purge-1.0 …
  Nginx通过upstream模块来实现简单的负载均衡,upstream需要定义在http段内
  在upstream段内,定义一个服务器列表,默认的方式是轮询,如果要确定同一个访问者发出的请求总是由同一个后端服务器来处理,可以设置ip_hash

环境

主机名IP所需服务
WangJiayue-4192.168.222.135Nginx
WangJiayue-3192.168.222.134httpd
WangJiayue192.168.222.139lnmp

16.1 配置静态Nginx页面

[root@WangJiayue-3 ~]# cd /var/www/html/
[root@WangJiayue-3 html]# ls
[root@WangJiayue-3 html]# echo 'WangJiayue-1' > index.html
[root@WangJiayue-3 html]# ls
index.html
[root@WangJiayue-3 html]# ss -antl
State       Recv-Q Send-Q                                                     Local Address:Port                                                                    Peer Address:Port              
LISTEN      0      128                                                                    *:22                                                                                 *:*                  
LISTEN      0      100                                                            127.0.0.1:25                                                                                 *:*                  
LISTEN      0      128                                                                   :::80                                                                                :::*                  
LISTEN      0      128                                                                   :::22                                                                                :::*                  
LISTEN      0      100                                                                  ::1:25                                                                                :::*                  

在这里插入图片描述
访问成功

WangJiayue-4上搭建
lnmp配置请移至LNMP部署
在这里插入图片描述

16.2 WangJiayue-4上配置反向代理

[root@WangJiayue-4 ~]# vim /usr/local/nginx/conf/nginx.conf

//添加以下内容
	upstream WangJiayue.com {
		server 192.168.222.134 weight=2;      
		server 192.168.222.139 weight=1;
    }

......
        #access_log  logs/host.access.log  main;

        location / {
             proxy_pass http://WangJiayue.com;  
        }
......

[root@WangJiayue-4 ~]# 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@WangJiayue-4 ~]# nginx -s reload

用浏览器访问WangJiayue(192.168.222.135)

首次访问
在这里插入图片描述

二次访问
在这里插入图片描述

三次访问跳转
在这里插入图片描述

16.3 动静分离

[root@WangJiayue-4 ~]# vim /usr/local/nginx/conf/nginx.conf

upstream static {
    server 192.168.222.139 weight=1;
}

upstream danamic {
    server 192.168.232.134 weight=1;
}

    server {
        listen       80;
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
            proxy_pass http://static;
            root   html;
            index  index.html index.htm;
        }

        location ~ \.php$ {
            proxy_pass http://danamic;
        }

[root@WangJiayue-4~]# 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@WangJiayue-4 ~]# nginx -s reload

在这里插入图片描述
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值