1. Nginx介绍

Nginx简介

  • Nginxx是lgor Sysoev为俄罗斯访问量第二的rambler.ru站点设计开发的。从2004年发布至今,凭借 开源的力量, 已经接近成熟与完善
  • Nginx是一个高性能的HTTP和反向代理服务器,也可作邮件服务器
  • 支持FastCGI、 SSL、Virtual Host、URL Rewrite、Gzip等功能。并且支持很多第三方的模块扩展。

Nginx特点

  • 支持高并发,消耗内存小,性能好

  • 具有多种功能

    • 静态资源web服务功能
    • 负载均衡功能
    • 网站缓存功能
  • 跨平台部署

  • 基于事件驱动架构,使用异步网络IO模型:epoll模型

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

  • 模块化设计,较好拓展性

  • web服务相关功能:

    • 虚拟主机
    • 支持keep-alive和管道连接
    • 访问日志(支持基于日志缓冲提高性能)
    • url rewrite
    • 路径别名
    • 基于IP及用户的访问机制
    • 支持速率限制及并发数限制
    • 平滑加载:重新配置和在线升级而无须中断客户的工作进程
    • Memcached的GET接口

工作原理

  • Nginx由内核和一系列模块组成,内核提供web服务的基本功能,如启用网络协议,创建运行环境,接收和分配客户端请求,处理模块之间的交互。
  • Nginx的各种功能和操作都由模块来实现。Nginx的模块从结构上分为核心模块、标准模块和第三方模块。

    • 核心模块: core module
    • 标准模块:

      • HTTP模块:(web功能)ngxhttp*
      • Mail模块:(邮件功能)ngxmail*
      • Stream模块:(tcp/udp请求转发功能)ngxstream*
    • 第三方模块:

nginx用途

  1. 静态的web资源服务器
  2. html,图片,js,Css,txt等静态资源
  3. 结合FastCGI/uWSGI/SCGI等协议反向代理动态资源请求
  4. http/https协议的反向代理
  5. imap4/pop3协议的反向代理
  6. tcp/udp协议的请求转发(反向代理)

2. Nginx服务部署安装

  • yum安装,安装前需要先安装扩展源
  1. [root@localhost ~]# yum install-y epel-release.noarch
  2. [root@localhost ~]# yum install -y nginx
  • 启动nginx(建议用nginx自己命令)
  1. [root@localhost ~]# nginx
  • 关闭防火墙和selinux
  1. [root@localhost ~]# systemctl stop firewalld.service
  2. [root@localhost ~]# setenforce 0
  • 浏览器输入IP地址即可访问

Nginx目录结构介绍

路径信息 类型信息 作用说明
/etc/logrotate.conf 配置文件 用于日志轮询切割
/etc/nginx/nginx.conf
/etc/ngnix/conf.d/
/etc/nginx/nginx.conf.default
配置文件配置目录 nginx主配置文件
/etc/nginx/fastcgi_params
/etc/nginx/fastcgi_params.default
/etc/nginx/scgi_params
/etc/nginx/scgi_params.default
/etc/nginx/uwsgi_params /etc/nginx/uwsgi_params.default
配置文件 cgi、fastcgi、uwcgi配置文件
/etc/nginx/koi-utf
/etc/nginx/koi-win
配置文件 nginx编码映射文件
/etc/nginx/mime.types /etc/nginx/mime.types.default 配置文件 http协议的content-type与扩展 名
/usr/lib/systemd/system/nginx.service 配置文件 nginx服务守护进程管理文件
/etc/nginx/modules 目录信息 模块目录
/usr/sbin/nginx 命令信息 nginx模块管理
  1. ls /usr/local/nginx/
  2. #html是测试页, sbin是主程序
  3. ls /usr/local/nginx/sbin/
  4. #nginx只有一个程序文件
  5. ls /usr/local/nginx/html/
  6. #50x.htmI index.html测试网页
  7. Nginx :默认为启动nginx
  8. -h:看帮助选项
  9. -V:本和配置选项
  10. -t:试nginx语法错误
  11. -Cilename指定配置文件(default: /etc/nginx/nginx.conf)
  12. -Signal发送信号给master进程, signal : stop, quit, reopen, reload
  13. 示例: nginx -s top
  14. 停止nginx
  15. nginx -s reload
  16. 加载配置文件
  17. -g directives在命令行中指明全局指令

日志切割

  • /etc/logrotate.d/nginx:可以实现日志切割
  1. #日志切割方式一:
  2. mv /var/log/nginx/access.log /var/log/nginx/access_$(date +%F).log
  3. #平滑重启
  4. nginx -s reload
  5. # 日志切割方式二,使用专用的文件切割程序--logrotate
  6. [root@localhost logrotate.d]# cat /etc/logrotate.conf
  7. # see "man logrotate" for details
  8. # rotate log files weekly
  9. weekly # 定义默认日志切割周期
  10. # keep 4 weeks worth of backlogs
  11. rotate 4 # 定义只保留几个切割后的文件
  12. # create new (empty) log files after rotating old ones
  13. create # 切割后创建出一个相同的源文件,后面可以跟上文件权限、属主、属组
  14. # use date as a suffix of the rotated file
  15. dateext # 定义角标,扩展名称信息
  16. # uncomment this if you want your log files compressed
  17. #compress # 是否对切割后的文件进行压缩处理
  18. # RPM packages drop log rotation information into this directory
  19. include /etc/logrotate.d
  20. # no packages own wtmp and btmp -- we'll rotate them here
  21. /var/log/wtmp { # 当都对某个文件进行切割配置
  22. monthly
  23. create 0664 root utmp
  24. minsize 1M
  25. rotate 1
  26. }
  27. /var/log/btmp {
  28. missingok
  29. monthly
  30. create 0600 root utmp
  31. rotate 1
  32. }

配置文件

主配置文件

  1. [root@localhost ~]# cp /etc/nginx/nginx.conf{,.bak}
  2. [root@localhost ~]# grep -Ev "#|^$" /etc/nginx/nginx.conf.bak
  3. >/etc/nginx/nginx.conf
  • main区域
  1. [root@localhost ~]# cat /etc/nginx/nginx.conf
  2. =====================第一个部分,配置文件的主区域======================
  3. user nginx; # 定义worker进程的管理用户
  4. worker_processes auto; # 定义worker进程数,auto会自动调整为cpu核数
  5. worker_cpu_affinity auto [cpumask] #提高缓存命中率,将worker与cpu绑定
  6. CPU MASK00000001:第一个CPU
  7. 00000010:第二个CPU
  8. worker_cpu_affinity 0001 0010 0100 1000;
  9. worker_ priority number
  10. #指定worker进程的nice值,设定worker进程优先级: [-20,20](最大为19)
  11. worker_ rlimit_ nofile number #worker进程所能够打开的文件数量上限,如65535
  12. error_log /var/log/nginx/error.log; # 定义错误日志
  13. pid /run/nginx.pid; # 指定存储nginx主进程的PID文件路径
  14. include /usr/share/nginx/modules/*.conf; #指明包含进来的其他配置文件片段
  15. daemon on|off #是否以守护进程方式运行nginx
  16. master_ process on|off #是否以master/worker模型运行nginx,默认为on
  • 事件区域
  1. ...
  2. events {
  3. worker_connections 1024;
  4. # 定义一个worker进程可以同时接受1024个请求
  5. #总最大并发数: worker_processes * worker_ connections
  6. use method #指明并发连接请求的处理方法,默认为epoll
  7. use poll;
  8. accept_mutex on|off
  9. #处理新的连接请求的方法; on指由各个worker轮流处理新请求, Off指每个新请求的到达都会通知(唤醒)所有的worker进程,但只有一个进程可获得连接,造成 “惊群”,影响性能
  10. }
  • http区域
  1. ...
  2. http {
  3. log_format main '$remote_addr - $remote_user [$time_local] "$request" '
  4. '$status $body_bytes_sent "$http_referer" '
  5. '"$http_user_agent" "$http_x_forwarded_for"';
  6. # 定义日志格式
  7. access_log /var/log/nginx/access.log main; # 指定日志文件路径
  8. sendfile on; # 允许sendfile方式传输文件
  9. tcp_nopush on; # 在sendfile启动下,使用TCP_CORK套接字
  10. tcp_nodelay on; # 接连接保持活动状态
  11. keepalive_timeout 65; # 超时时间
  12. types_hash_max_size 2048;# 连接超时时间
  13. include /etc/nginx/mime.types; # 文件扩展名与文件类型映射表
  14. default_type application/octet-stream; # 默认文件类型,默认为text/plain
  15. include /etc/nginx/conf.d/*.conf; #虚拟主机目录
  16. server {
  17. listen 80 default_server; # 指定监听的端口
  18. listen [::]:80 default_server;
  19. server_name _; # 指定网站主机名
  20. root /usr/share/nginx/html; # 定义站点目录的位置
  21. include /etc/nginx/default.d/*.conf; # 定义首页文件
  22. location / {
  23. }
  24. error_page 404 /404.html; # 定义优雅显示页面信息
  25. location = /40x.html {
  26. }
  27. error_page 500 502 503 504 /50x.html;
  28. location = /50x.html {
  29. }
  30. }

日志说明

  1. $remote_addr$http_x_forwarded_for: 用以记录客户端的ip地址;
  2. $remote_user:用来记录客户端用户名称;
  3. $time_local:用来记录访问时间与时区;
  4. $request:用来记录请求的urlhttp协议;
  5. $status:用来记录请求状态;成功是200
  6. $body_bytes_s ent:记录发送给客户端文件主体内容大小;
  7. $http_referer:用来记录从那个页面链接访问过来的;
  8. $http_user_agent:记录客户端浏览器的相关信息

location表达式

  • 优先级:=,^/~,不带符号 | ~ | 表示执行一个正则匹配,区分大小写; | | —- | —- | | ~ | 表示执行一个正则匹配,不区分大小写 | | ^~ | 表示普通字符匹配。使用前缀匹配。如果匹配成功,则不再匹配其他location; | | = | = 进行普通字符精确匹配 | | @ | 它定义一个命名的 location,使用在内部定向时 |
  1. #精确匹配
  2. location = / {
  3. [ configuration A ]
  4. }
  5. location / {
  6. [ configuration B ]
  7. }
  8. location /documents/ {
  9. [ configuration C ]
  10. }
  11. #表示普通字符匹配
  12. location ^~ /images/ {
  13. [ configuration D ]
  14. }
  15. location ~* \.(gif|jpg|jpeg)$ {
  16. [ configuration E ]
  17. }
  18. A:请求 /
  19. B: 请求 index.html
  20. C: 请求 /documents/document.html
  21. D: 请求 /images/1.jpg
  22. E: 请求 /documents/document.gif

客户端相关配置

keepalive_timeout # 保持连接的超时时长
keepalive_requests # 一次连接允许请求资源的最大数量
keepalive_disable # 对某种浏览器禁用长连接
send_timeout # 向客户端发送响应报文的超时时长
client_body_buffer_size # 接收客户端请求报文的body部分的缓冲区大小
client_body_temp_path # 设定用于存储客户端请求报文的body部分的临时存储路径及子目录结构和数量
limit_rate rate # 限制响应给客户端的传输速率
limit_except # 限制对指定的请求方法之外的其它方法的使用客户端

3. 搭建网站

  • 配置文件
[root@www conf.d]# vim /etc/nginx/conf.d/www.conf
server {
    listen *:8080;
    server_name www.eagle.com;
    location / {
        root /usr/share/nginx/html; #站点位置
        index ealgeslab.html;
    }
}
  • 编写html文件并赋予权限
[root@www ~]# vim /usr/share/nginx/html/ealgeslab.html
<h1>
my first web!
</h1>

#[root@www ~]# chmod 777 /usr/share/nginx/html/ealgeslab.html
  • 编写hosts文件,做好域名解析

    • (如果windows需要访问也要在这个目录下的hosts文件做相同操作 C:\Windows\System32\drivers\etc)
[root@www ~]# cat /etc/hosts
...
192.168.33.133 www.eagle.com
...
[root@www ~]# ping www.eagle.com
  • 重启nginx服务(使用reload平滑重启,以下两种方式不要混用)
[root@www html]# nginx -s reload
或者
[root@www html]# systemctl reload nginx.service
  • 关闭防火墙和selinux
[root@www ~]# systemctl stop firwalld
[root@www ~]# setenforce 0
  • 测试
[root@www ~]# curl www.eagle.com:8080

搭建多个网站

  • 相关配置文件
[root@www ]# touch /etc/nginx/conf.d/{bbs,blog,www}.conf
[root@www ]# cd /etc/nginx/conf.d/

[root@www conf.d]#vim bbs.conf
server {
    listen *:8080;
    server_name bbs.eagle.com;
    location / {
        root /html/bbs;
        index index.html;
    }
}

[root@www conf.d]#vim blog.conf
server {
    listen *:8080;
    server_name blog.eagle.com;
    location / {
        root /html/blog;
        index index.html;
    }
}

[root@www conf.d]#vim www.conf
server {
    listen *:8080;
    server_name www.eagle.com;
    location / {
        root /html/www;
        index index.html;
    }
}
  • 准备站点目录并赋予权限
[root@www ]# mkdir -p /html/{www,bbs,blog}
[root@www bbs]# for name in {www,bbs,blog};do echo "<h1> $name </h1>" >
/html/$name/index.html;done;

[root@www ~]# chmod -R 777 /html
  • 域名解析
[root@www ]# cat /etc/hosts
192.168.33.133 www.eagle.com bbs.eagle.com blog.eagle.com
  • 关闭防火墙和selinux
[root@www ~]# systemctl stop firwalld
[root@www ~]# setenforce 0
  • 重启
[root@www ~]# nginx -s reload
  • 访问测试
[root@www ~]# curl www.eagle.com:8080
<h1> www </h1>

[root@www ~]# curl bbs.eagle.com:8080

<h1> bbs </h1>

[root@www ~]# curl blog.eagle.com:8080
<h1> blog </h1>

4. 核心模块之http模块

core_module

  • 配置虚拟主机
server{
    listen adress[:PORT]PORT;
    server_name SERVER_NAME;
    root /PATH/TO/DOCUMENT_ROOT;
}
#例子
[root@www ~]# vim a.com.conf
server{
    listen 80;
    server_name www.a.com;
    root /data/web1;
    location / {
    }
}
  • listen相关
default_ server #设定为默认虚拟主机
ssl #限制仅能够通过ssl连接提供服务
backlog = number #超过并发连接数后,新请求进入后援队列的长度
rcvbuf= size #接收缓冲区大小
sndbuf=size #发送缓冲区大小

基于PORT
    listen PORT; #监听在不同端口
基于ip
    listen IP:PORT #IP地址不同
基于hostnam
    server_name fqdn; #主机名不同
  • server_name相关

    • 虚拟主机的主机名称后可跟多个由空白字符分隔的字符串
    • 支持*通配任意长度的任意字符
    • 支持起始的字符做正则表达式模式匹配,性能原因慎用
匹配优先级机制从高到低:
(1)首先是字符串精确匹配如: www.magedu.com
(2)左侧*通配符如: *.magedu.com
(3)右侧通配符如: www.magedu.
(4)正则表达式如: ~^.*\.magedul.com$
(5) default_ server
  • 路径相关

    • 设置web资源的路径映射;用于指明请求的URL所对应的文档的目录路径

    • 用于http, server, location, if in location
server {
    root data/www/vhost;
}

http://www.magedu.com/images/logojpg --> /data/www/vhost/images/logojpg
  • location相关

    • 在一个server中location配置段可存在多个,用于实现从uri到文件系统的路
      径映射
    • ngnix会根据用户请求的URI来检查定义的所有location ,并找出一个最
      佳匹配,而后应用其配置
server{
    server_name www.salted.com;
    location /images/{
        root /data/imgs/;
    }
}

http://www.magedu.com/images/logo.jpg -- > /data/imgs/images/logo.jpg
server{
    listen 80;
    server_name www.salted.com;
    root /www/html/
    location /images/{
        root /data/imgs/;
    }
}
http://www.magedu.com/index.html --> /www/html/index.html
http://www.magedu.com/images/index.html --> /data/imgs/images/index.html
  • 路径别名

    • alias path:路径别名,文档映射的另一种机制
    • 仅能用于location上下文
server{
    listen 80;
    server_name www.salted.com
    location /bbs/{
        alias /web/forum/;
    }  
    #www.salted.com/bbs/index.html --> /web/forum/index.html

    location /bbs/{
        root /web/forum/;
    } 
    www.salted.com/bbs/index.html  --> /web/forum/bbs/index.html
}
  • 错误页面

    • 定义错误页,并可以指定响应状态码进行响应
    • http,server,location上下文
#指定错误页
server{
    listen 80;
    server_name www.salted.com;
    error_page 404 /404.html;
    location /404.html {
        root /data/error/;
    }

}

#指定响应状态码
server{
    listen 80;
    server_name www.salted.com;
    error_page 404=200 /404.html; #返回200状态码,但页面还是404页面
    location /404.html {
        root /data/error/;
    }

}
  • 检查文件

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

location /images/{
    try_files $uri /images/default.gif;
}

location /images/{
    try_files $uri=404;
}
  • 客户端限制
limit_ rate rate;
    #限制响应给客户端的传输速率,单位是bytes/second,默认值0表示无限制

limit_ except method .. { ..}.仅用于location
    #限制客户端使用除了指定的请求方法之外的其它方法
method:GET, HEAD, POST, PUT, DELETE
MKCOL, COPY, MOVE, OPTIONS, PROPFIND,
PROPPATCH, LOCK, UNLOCK, PATCH

server{
    liseten 80;
    server_name www.salted.com;
    location / {
        root /data/web;
        limit_ except GET {
            allow 192.168.1.0/24;
            deny all;
        }#除了GET和HEAD之外其他方法仅允许192.168.1.0/24网段主句使用
    }
}
  • 文件操作优化
aio on | off | threads[=pool;
    #是否启用aio功能

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

open_file_cache off;
open. _file_cache max=N [inactive= time];
    nginx可以缓存以下三种信息:
    (1)文件元数据:文件的描述符、文件大小和最近一次的修改时间
    (2)打开的目录结构
    (3)没有找到的或者没有权限访问的文件的相关信息
max=N :#可缓存的缓存项上限;达到上限后会使用LRU算法实现管理
inactive=time :#缓存项的非活动时长,在此处指定的时长内未被命中的或命中的次数少于open_ file_ cache_ min_ _uses指令 所指定的次数的缓存项即为非活动项,将被删除

open_ file_ cache_ errors on| off;
    #是否缓存查找时发生错误的文件一类的信息默认值为off

open_file_ cache_ _min_ _uses number;
    #open_ file_ cache指令的inactive参数指定的时长内,至少被命中此处指定的次数方可被归类为活动项,默认值为1

open_ file_ cache_valid time;
    #缓存项有效性的检查频率默认值为60s .
  • 其他相关
tcp_nodelay on|off;
    #在keepalived模式下的连接是否启用TCP_ _NODEL AY选项
    #当为off时,延迟发送,合并多个请求后再发送
    #默认On时,不延迟发送
    #可用于: http, server, location

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

server_ tokens on | off I build | string
    #是否在响应报文的Server首部显示nginx版本
    #默认是on

定义客户端请求的相关配置
keepalive_ _timeout timeout [header_ _timeout];
    #设定保持连接超时时长, 0表示禁止长连接,默认为75s

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

keepalive_ disable none | browser.
    #对哪种浏览器禁用长连接

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

access_module

  • 基于IP地址的访问控制功能

    • 自上而下检查,一旦匹配将生效
    • 条件严格的应该置前
server {
    ...
    deny 192.168.1.1;
    allow 192.168.1.0/24;
    allow 10.1.1.0/16;
    allow 2001:0db8::/32;
    deny all;
}

server{
    ...
    location{
        deny 192.168.1.1;
        allow 192.168.1.0/24;
        allow 10.1.1.0/16;
    }

}

auth_basic_module

  • 使用基于用户的访问控制,使用basic机制进行用户认证
  • httpd-tools提供

    • 网站验证;特定路径验证
location / {
    auth_basic "login info"; #提示信息
    auth_basic_user_file /etc/nginx/conf.d/htpasswd; #用户文件
}
    下载相关工具并创建用户
[root@www ~]# htpasswd -bc /etc/nginx/conf.d/htpasswd httpuser1 123456
[root@www ~]# htpasswd -bm /etc/nginx/conf.d/htpasswd httpuser2 123456
[root@www ~]# htpasswd -bc /etc/nginx/conf.d/nginxuser httpuser1 123456
    htpasswd工具介绍
-c:创建一个密码文件,第一次需要写上去
-n:不会更新文件,显示文件内容信息
-b:免交互式输入用户密码信息
-i:读取密码采用标准输入方式,并不做检查
-m:使用md5的加密算法
-B:使用bcrypt对密码进行加密
-C:使用bcrypt algorithm对密码进行加密
-d:密码加密方式
-s:加密方式
-p:不进行加密
-D:删除指定用户

stub_status_module

用于输出nginx的基本状态信息
输出信息示例:
    Active connections: 291
    server accepts handled requests
        16630948 16630948 31070465
上面三个数字分别对应accepts,handled,requests三个值
Reading: 6 Writing: 179 Waiting: 106
location = /basic_status {
    stub_status;
}

log_module

相关日志的设置
#日志格式
log_format main '$remote_addr - $remote_user [$time_local] '
                    '"$request" $status $bytes_sent '
                    '"$http_referer" "$http_user_agent" "$gzip_ratio"';

#访问日志路径,格式以及相关的缓冲配置
access_log /var/log/nginx/access.log main buffer=32k;
#主配置文件里面
[root@www ~]# vim /etc/nginx/nginx.conf
...
http{
    log_format main '$remote_addr - $remote_user [$time_local] '
                    '"$request" $status $bytes_sent '
                    '"$http_referer" "$http_user_agent" "$gzip_ratio"';
    log_format testlog '$remote_addr - $remote_user [$time_local] '
                    '"$request" $status $bytes_sent '

    access_log /var/log/nginx/access.log main;
}

#虚拟主机配置
server{
    listen 80;
    server_name www.salted.com;
    access_log testlog; #挑选日志
    location /{
        ...
    }
}
  • 相关配置参数
open_log_ file_ cache max=N [inactive=time] [min_ _uses=N]
[valid =time];
open_ log_file_ cache off;
    缓存各日志文件相关的元数据信息
    max :缓存的最大文件描述符数量
    min_uses :在inactive指定的时长内访问大于等于此值方可被当作活动项
    inactive :非活动时长
    valid :验证缓存中各缓存项是否为活动项的时间间隔

gzip_module

  • 使用gzip方式压缩响应数据,节约带宽
gzip on| off;
    #启用或禁用gzip压缩

gzip_ comp_ level level;
    #压缩比由低到高:1到9,默认1

gzip_ disable regex ..;
    #匹配到客户端浏览器不执行压缩

gzip_ min_ length length;
    #启用压缩功能的响应报文大小阈值

gzip_ http. _version 1.0| 1.1;
    #设定启用压缩功能时,协议的最小版本,默认: 1.1

gzip_ buffers number size;
    #支持实现压缩功能时缓冲区数量及每个缓存区的大小,默认:324k或168k

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

gzip_ vary on | off; .
    #如果启用压缩,是否在响应报文首部插入并显示"Vary: Accept-Encoding"

gzip_ proxied off | expired| no-cache | no-store| private|
no_ last_ modified| no_ etag| auth| any ...
    #nginx充当代理服务器时,对于后端服务器的响应报文,在何种条件下启用压缩功能
    #off :不启用压缩
    #expired,no-cache,no-store,private :对后端服务器的响应报首部Cache-Control值任何一个,启用压缩功能
#案例
gzip on;
gzip_min_length 1000;
gzip_proxied any;
gzip_types text/plain application/xml;

ssl_module

定义https的相关配置
http {
...
server {
    ...
    listen                 443 ssl;
    keepalive_timeout     70;
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    ssl_ciphers AES128-SHA:AES256-SHA:RC4-SHA:DES-CBC3-SHA:RC4-MD5;
    ssl_certificate /usr/local/nginx/conf/cert.pem;
    ssl_certificate_key /usr/local/nginx/conf/cert.key;
    ssl_session_cache shared:SSL:10m;
    ssl_session_timeout 10m;
    ...
}

rewrite_module

将用户请求的URI基于regex所描述的模式进行检查,而后完成替换

referer_module

定义referer首部的合法可用值

5. 负载均衡

负载均衡算法

七层

网络拓扑

Nginx主机配置

  • 下载拓展源和nginx
[root@nginx ~]# yum install -y nginx
  • 关闭防火墙和selinux
[root@nginx ~]# setenforce 0
[root@nginx ~]# systemctl stop firewalld
  • 负载均衡配置文件
[root@nginx ~]# vim /etc/nginx/conf.d/proxy.conf 
upstream webserver{
        server 192.168.244.128;
        server 192.168.244.129;
}
server {
        listen 80;
        server_name www.salted.com;
        location / {
                proxy_pass http://webserver;
        }

}
[root@nginx ~]# nginx -s reload

#也可以添加权重
upstream webserver{
        server 192.168.244.128 weight=1;
        server 192.168.244.129 weight=2;
}

RS1配置

  • 下载并启动apache服务
[root@RS1 ~]# yum install -y httpd
[root@RS1 ~]# systemctl start httpd
[root@RS1 ~]# ss -tanl 
State      Recv-Q Send-Q       Local Address:Port                      Peer Address:Port              
...                                 *:*                  
LISTEN     0      128                     :::80                           ...
  • 关闭防火墙和selinux
[root@RS1 ~]# setenforce 0
[root@RS1 ~]# systemctl stop firewalld
  • 搭建web站点1
[root@RS1 ~]# vim /var/www/html/index.html
<h1>
welcome to my home RS1! 
</h1>
[root@RS1 ~]# systemctl restart httpd

RS2配置

  • 下载并启动apache服务
[root@RS2 ~]# yum install -y httpd
[root@RS2 ~]# systemctl start httpd
[root@RS2 ~]# ss -tanl 
State      Recv-Q Send-Q       Local Address:Port                      Peer Address:Port              
...                                 *:*                  
LISTEN     0      128                     :::80                           ...
  • 关闭防火墙和selinux
[root@RS2 ~]# setenforce 0
[root@RS2 ~]# systemctl stop firewalld
  • 搭建web站点2
[root@RS2 ~]# vim /var/www/html/index.html
<h1>
welcome to my home RS2! 
</h1>
[root@RS2 ~]# systemctl restart httpd

四层

image-20210407201132197

  • 四层负载均衡配置文件

    • !!stream模块只能写进主配置文件里面
[root@salted ~]# vim /etc/nginx/nginx.conf
。。。
stream {
    server {
       listen 22222;
       proxy_pass web;
    }
    upstream web {
       server 192.168.244.128:22;
       server 192.168.244.129:22;
    }
}
。。。
[root@salted ~]# nginx -s reload
  • 测试:使用ssh协议测试