Nginx基本使用说明

Nginx

1.Nginx功能特性

1.1.Nginx常用的功能模块

静态资源的部署

Rewrite地址重写

​ 正则表达式

方向代理

负载均衡

  • 轮询,加权轮询,ip_hash,url_hash,fair

Web缓存

环境部署

  • 高可用的环境

用户认证模块

1.2.Nginx的核心组成

nginx二进制可执行文件

nginx.conf配置文件

error.log错误的日志记录

access.log访问日志记录

2.Nginx环境配置

1.环境配置

Index of /download/ (nginx.org)

使用sestatus查看,将sestatus关闭

vim /etc/selinux/config

修改SELINUX=disabled

2.通过nginx源码安装

1.gcc

yum install -y gcc

2.pcre

yum install -y pcre pcre-devel

3.zlib

yum install -y zlib zlib-devel

4.openSSL

yum install -y openssl openssl-devel

5.使用wget安装

wget https://nginx.org/download/nginx-1.26.1.tar.gz
//创建文件,便于管理
mkdir -p nginx/core
mv nginx-1.26.1.tar.gz nginx/core

6.解压缩

tar -xzf nginx-1.26.1.tar.gz

7.进入./configure

8.编译

没有make可以安装一下

yum -y install make

make

9.安装

make install

没有指定安装目录,可能在/usr/local/nginx/sbin

./nginx

在浏览器输入ip访问nginx

当结果为如下界面时,测试成功

请添加图片描述

3.通过yum安装

yum install -y yum-utils

sudo yum install -y nginx

4.通过nginx源码进行复杂安装

安装目录

–prefix=PATH

指向执行程序文件路径

–sbin-path=PATH

指向nginx.conf的路径

–conf-path=PATH

重新卸载nginx

rm -rf /usr/local/nginx

make clean

./configure --prefix=/usr/local/nginx --sbin-path=/usr/local/nginx/sbin/nginx --modules-path=/usr/local/nginx/modules --conf-path=/usr/local/nginx/conf/nginx.conf --error-log-path=/usr/local/nginx/logs/error.log --http-log-path=/usr/local/nginx/logs/access.log --pid-path=/usr/local/nginx/logs/nginx.pid --lock-path=/usr/local/nginx/logs/nginx.lock

5.Nginx目录结构

yum install -y tree 使用tree来查看项目结构

CGI通用网关(接口),从客户端发送一个请求和数据,服务端获取到请求和数据可以调用CGI程序处理及相应结果给客户端的一种标准规范

[root@localhost sbin]# tree /usr/local/nginx
/usr/local/nginx
├── client_body_temp
├── conf
│ ├── fastcgi.conf
│ ├── fastcgi.conf.default
│ ├── fastcgi_params
│ ├── fastcgi_params.default
│ ├── koi-utf
│ ├── koi-win
│ ├── mime.types
│ ├── mime.types.default
│ ├── nginx.conf
│ ├── nginx.conf.default
│ ├── scgi_params
│ ├── scgi_params.default
│ ├── uwsgi_params
│ ├── uwsgi_params.default
│ └── win-utf
├── fastcgi_temp
├── html
│ ├── 50x.html
│ └── index.html
├── logs
│ ├── access.log
│ ├── error.log
│ └── nginx.pid
├── proxy_temp
├── sbin
│ └── nginx
├── scgi_temp
└── uwsgi_temp

3.Nginx服务的启停

1.Nginx服务的信号控制

2.Nginx的命令行控制

3.1.Nginx服务的信号控制

nginx默认采用多进程的方式来工作

ps -ef | grep nginx

root       31002       1  0 09:36 ?        00:00:00 nginx: master process ./nginx
nobody     31003   31002  0 09:36 ?        00:00:00 nginx: worker process
root       87869    2359  0 10:00 pts/0    00:00:00 grep --color=auto nginx

发送信号给master进程来控制worker进程等

3.2.信号

信号作用
TERM/INT立即关闭服务
QUIT等待并关闭服务
HUP重读配置文件并使用
USR1重新打开日志文件,可以用来进行日志切割
USR2平滑升级到最新的Nginx
WINCH给所有work进程发送QUIT指令

kill -signal pid

例:

kill -QUIT 13636

​ kill -QUIT `more …/logs/nginx.pid`

发送USR2信号给master进程,告诉master进程要平滑升级,这个时候,会重新开启对应的master进程和work进程,整个系统中将会有两个master进程,并且新的master进程的PID会被记录在/usr/1oca1/nginx/1ogs/nginx.pid而之前的旧的master进程PID会被记录在/usr/1oca1/nginx/1ogs/nginx.pid.oldbin文件中,接着再次发送QUIT信号给旧的master进程,让其处理完请求后再进行关闭
kill -USR2 PID / kill -USR2 'cat /usr/local/nginx/logs/nginx.pid"

kill -QUIT PID / kill -QUIT `cat /usr/loca1/nginx/1ogs/nginx.pid.oldbin`

发送WINCH信号给master进程,让master进程控制不让所有的work进程在接收新的请求了,请求处理完后关闭work进程。注意master进程不会被关闭掉 kill -WINCH PID /ki11 -WINCH`cat /usr/local/nginx/logs/nginx.pid"

3.3.Nginx的命令行控制

-?,-h : this help

-v : show version and exit

-V : show version and configure options then exit

-t : test configuration and exit

  • 检测nginx.conf的语法

-T : test configuration, dump it and exit

  • 检测nginx.conf的语法,成功打印测试文件

-q : suppress non-error messages during configuration testing

-s signal : send signal to a master process: stop, quit, reopen, reload

  • stop 快速关闭
  • quit 等待关闭
  • reopen 类似USR1
  • reload 类似HUP

-p prefix : set prefix path (default: /usr/local/nginx/)

  • 指定nginx的prefix路径

-e filename : set error log file (default: /usr/local/nginx/logs/error.log)

  • 设置日志路径

-c filename : set configuration file (default: /usr/local/nginx/conf/nginx.conf)

  • 设置配置文件路径

-g directives : set global directives out of configuration file

  • 用来补充Nginx配置文件,向nginx服务指定启动时应用的全局的配置
  • ./nginx -g “pid logs/abc.pid;”

3.4.版本升级

3.4.1使用nginx服务信号

cd /usr/local/nginx/sbin

mv nginx nginxold

cd ~/nginx/core/nginx-1.16.1/objs

cp nginx /usr/local/nginx/sbin

查看nginx进程pid

ps -ef | grep nginx

平滑升级

kill -USR2 `cat /usr/local/nginx/logs/nginx.pid`

//关闭旧进程

kill -QUIT `cat /usr/local/nginx/logs/nginx.oldbin`

3.4.2使用make命令

cd /usr/local/nginx/sbin

mv nginx nginxold

cd ~/nginx/core/nginx-1.16.1/objs

cp nginx /usr/local/nginx/sbin

进入安装目录,执行make upgrade

查看是否更新完成

./nginx -V

4.config配置目录

  • 全局块,events块,http块
  • http块中可以配置多个serve块,每个serve块又可以配置多个location块
#user  nobody;
worker_processes  1;

events {
    worker_connections  1024;
}

http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;

    server {
        listen       80;
        server_name  localhost;
        location / {
            root   html;
            index  index.html index.htm;
        }
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    }
}

4.1全局块

4.1.1user指令

(1)user用于配置运行nginx服务器的worker进程的用户和用户组

语法user user [group]
默认值nobody
位置全局块

该属性也可以在编译时指定 ./configure --user=user --group=group

使用步骤

1.设置一个用户信息www,在nginx.conf设置,但是会报一个没有该用户的错误,此时需要useradd www

user www 测试./nginx -t

[root@localhost sbin]# ./nginx -t
nginx: [emerg] getpwnam("www") failed in /usr/local/nginx/conf/nginx.conf:2
nginx: configuration file /usr/local/nginx/conf/nginx.conf test failed

2.此时如果将html查询的目录改为 /root/html -->此时会403,权限不足

因此我们可以改为/home/www/html此时便可以访问index.html页面

user指令可以指定启动运行工作进程的用户和用户组,这样对于系统的权限访问控制更加精细,也更加安全

4.1.2work_process指令

master_process指定是否开启工作进程

语法master_process on | off
默认值master_process on
位置全局块

用于配置nginx生产工作进程的数量,建议将该值与服务器cpu的内核数保持一致

语法worker_processes num/auto
默认值1
位置全局块

如果设置为2

请添加图片描述

4.1.3其他指令

daemon:设定nginx是否以守护进程的方式启动

守护进程是linux后台执行的一种服务进程,特点是独立于控制终端,不会随着终端的关闭而停止

语法daemon on/off
默认值daemon on
位置全局块

pid:用来配置nginx当前master进程号ID存储的文件路径

语法pid file
默认值/usr/local/nginx/logs/nginx.pid
位置全局块

error log配置错误日志存放路径

语法error_log file [日志级别]
默认值/usr/local/nginx/logs/nginx.pid
位置全局块、http、serve、location

日志级别:debug info notice warn error crit alert emerg -->建议不要使用info一下级别

include:用来引入其他配置文件,使nginx的配置更加灵活

语法include file
默认值
位置any

include main.conf —>可以将一部分配置写入main.conf文件中

4.2events块

(1)accept_mutex用来设置nginx网络连接序列化

语法accept_mutex on|off
默认值accept_mutex on
位置events

解决"惊群问题"

(2)multi_accept:用来设置是否允许同时接受多个网络连接

语法multi_accept on|off
默认值multi_accept off
位置events

建议开启on

(3)worker connections:用来配置单个worker进程最大的连接数

语法worker_connections number
默认值worker_connections 512
位置events

(4)use:用来设置nginx服务器选择哪种事件驱动来处理网络消息

语法use method
默认值根据操作系统定
位置events

method --> select/poll/epoll/kqueue

建议设置epoll

4.2.1指令配置实例
events{
	accept_muyex on;
	multi_accpet on;
	worker_commections 1024;
	use epoll;
}
启动测试
./nginx -t
./nginx -s reload

4.3http块

(1)default_type:用来配置nginx响应前端请求默认的MIME类型

语法default_type mime-type
默认值default_type text/plain
位置http、server、location

(2)有些时候请求某些接口需要返回指定的文本字符串或者json字符串,如果逻辑非常简单或者干脆是固定的字符串,那么可以用nginx快速实现,减少服务器资源占用提升性能

(3)

access.log用来记录用户访问的请求

error.log记录nginx本身运行时的错误信息,不会记录用户的访问请求

(4)access_log用来设置用户访问日志的相关属性

语法access_log path[format[buffer=size]]
默认值access_log logs/access.log combined
位置http、server、location

(5)log_format:用来指定日志的输出格式

语法log_format name [escape=default|json|none] string
默认值log_format combined “…”
位置http

log_format myformat “========>”;

access_log logs/mylog.log myformat;

(6)sendfile:设置是否用sendfile传输文件,可大大提升nginx处理静态资源的性能

语法sendfile on | off
默认值sendfile off
位置http

(7)keepalive_timeout用来设置长连接的超时时间

语法keepalive_timeout time
默认值keepalive_timeout 75s
位置http、server、location

(7)keepalive_requests用来设置keep-alive的次数

语法keepalive_requests number
默认值keepalive_requests 100
位置http、server、location

4.4server和location块

    server {
        listen       80;
        server_name  localhost;
        location / {
            root   html;
            index  index.html index.htm;
        }
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    }

4.5基础配置实例

user  www;
worker_processes 2;
err_log logs/error.log;
pid logs/nginx.pid;

events {
    accept_mutex on;
    multi_accept on;
    use epool;
    worker_connections  1024;
}

http {
    include       mime.types;
    default_type  application/octet-stream;
    log_format serve1 '======>server1';
    log_format serve2 '======>server2'
    include /home/www/conf.d/*.conf;
 	sendfile        on;
    keepalive_timeout  65;

    server {
        listen       80;
        server_name  localhost;
        location / {
            root   html;
            index  index.html index.htm;
        }
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
}

4.6nginx配置成系统服务

(1)vim /usr/lib/systemd/system/nginx.service

[Unit]
Description=nginx web service
Documentation=http://nginx.org/en/docs
After=network.target

[Service]
Type=forking
PIDFile=/usr/local/nginx/logs/nginx.pid
ExecStartPre=/usr/local/nginx/sbin/nginx -t -c
/usr/local/nginx/conf/nginx.conf
ExecStart=/usr/local/nginx/sbin/nginx
ExexReload=/usr/local/nginx/sbin/nginx -s reload
ExecStop=/usr/local/nginx/sbin/nginx -s stop
PrivateTmp=true

[Install]
wantedBy=defauly.target

(2)chmod 755 /usr/lib/systemd/system/nginx.service

(3)使用系统命令操作

启动:systemctl start nginx

停止:systemctl stop nginx

重启:systemctl restart nginx

重新加载配置文件:systemctl reload nginx

查看nginx状态:systemctl status nginx

开机启动:systemctl enable nginx

4.7Nginx命令配置到系统环境

1.vim /etc/profile

export PATH=$PATH:/usr/local/nginx/sbin

2.source /etc/peofile

5.Nginx静态资源部署

5.11.listen

语法listen address[:port] [default_server]…
默认值listen *:80 | *:8000
位置server

default_server属性时标识符号,用来设置默认主机

server{
	listen 8080 default_server
}

5.22.server_name

设置虚拟主机服务名称

127.0.0.1 localhost 域名

语法server_name name…;
默认值server_name “”;
位置server

精确匹配

通配符匹配

正则表达式匹配

5.2.1精确匹配
server{
	server_name www.nginx.org;
}

hosts是一个没有扩展名的系统文件

Windows:C:\Windows\System32\drivers\etc

centos:/etc/hosts

5.2.2通配符匹配

通配符可以出现在开头或结尾,但不能用在域名的中部

server{
	server_name *.richu.cn 
}
5.2.3正则表达式匹配

1.正则表达式和分组

由于Nginx配置文件中经常出现正则表达式,因此本章节专门对常见的正则表达式进行简单介绍。

[1] 开始与结束

^表示匹配输入字符串的开始

$表示匹配输入字符串的结束

[2] 匹配次数

?表示匹配0次或者1次

+表示匹配1次或多次

*表示匹配0从或多次

{n}匹配n次,{n,}至少匹配n次,{n,m} 匹配n至m次

[3] 匹配字符

\符号用于转义

.匹配除\n之外的任意字符

[xyz]表示匹配xyz中任意一个字符

[a-z]表示匹配任意小写字母;[^a-z]取反,表示匹配除小写字母之外的任意字符;

[A-Z]表示匹配任意大写字母;[a-zA-Z]匹配任意字母;

[0-9]表示匹配任意数字, 等价于\d; [^0-9]表示匹配任意数字, 等价于\D

\s匹配任何空白字符;\S匹配任何非空白字符;

\w A-Z a-z 0-9

x|y 表示匹配x或y

在前面加上~表示为正则表达式

server_name example.com ~^www\d+.example.com$

server_name ~^www\.(\w+)\.com

location / {

​ return 200 $1 $2

}

$1可以匹配到(\w+)中匹配的内容

5.2.4匹配执行顺序

精确匹配 —》 通配符在开始 —》 通配符在结尾 —》正则表达式 —》默认default_server;

5.3location

用来设置请求的url

语法location [ = | ~ ~* ^- | @] uri{…}
默认值----
位置server,location

=用在不包含正则表达式的uri前面,必须与指定的内容精确匹配

location =/abc {
	
}

~ 正则匹配,区分大小写

~*正则匹配,不区分大小写

^~用于不包含正则表达式的uri前面,功能与不加符号一致,唯一不同的是,如果模式匹配,那么就会停止搜索其他模式

5.4root/alias

root:设置请求的根目录

语法root path
默认值root html
位置http、server、location

alias:用来更改location的url

语法alias path
默认值----
位置location

root:root路径加location后面的地址

alias:不会加上location后面的地址

  • alias是目录别名的定义

5.5index

index 设置网站的默认首页

语法index file …
默认值index index.html;
位置http、server、location

后面可以配置多个选项,当一个匹配之后就不会再匹配后面的设置

5.6error_page

设置网站的错误页面

语法index file …
默认值index index.html;
位置http、server、location

(1)可以跳转指定页面

error_page 404 www.richu.cn

(2)重定向地址

error _page 404 /50x.html

(3)使用location的@符号完成错误信息的匹配

server{
	error_page 404 @jump_to_error;
	location @jump_to_error {
		default_type text/plain;
		return 404 'Not Found Html'
	}
}

(4)可选项=[response]的作用是将相应的代码更改为另一个

error_page 404 =200 /50x.html

6.静态资源优化配置语法

6.1.sendfile

用来开启高效的文件传输模式

语法sendfile on|off
默认值sendfile off;
位置http、server、location
6.2.tcp_nopush

需要打开sendfile用来提升网络包传输效率

语法tcp_nopush on|off
默认值tcp_nopush off;
位置http、server、location
6.3.tcp_nodelay

需要打开keep-alive用来提升网络包传输的实时性

语法tcp_nodelay on|off
默认值tcp_nodelay on;
位置http、server、location

sendfile on

tcp_nopush in

tcp_nodealy on

6.4.gizp

开启或关闭gzip功能

语法gzip on|off
默认值gzip off;
位置http、server、location
6.5.gzip_types
语法gzip_types mime-type
默认值gzip_types text/html;
位置http、server、location

根据响应页面的MIME类型选择性开启Gzip压缩功能

gzip_types *;

6.6.gzip_comp_level

设置压缩程度,1-9,1程度低,效率高,9程度高,效率低。

语法gzip_comp_level level
默认值gzip_comp_level 1;
位置http、server、location
6.7.gzip_vary

告诉接收方,所发送的数据经过了gzip压缩处理

vary:Accrpt-Encoding

语法gzip_vary on|off
默认值gzip_vary off;
位置http、server、location
6.8.gzip_buffers

处理请求压缩的缓冲区数量和大小

语法gzip_buffers number size
默认值gzip_buffers 32 4k | 16 8k;
位置http、server、location

number为Nginx服务器向系统申请缓存空间数量,size指的是每个缓冲空间的大小。

建议不用设置,使用默认值即可

6.9.gzip_disable

针对不同的客户端发起的请求,可以选择性开启和关闭Gzip

语法gzip_disable regex …;
默认值
位置http、server、location

regex根据user-agent来设置,支持正则表达式

gzip_disable “MSIE [1-6]\.”; 禁用IE1-6版本的gzip

6.10.gzip_http_version:

针对不同的Http协议版本,可以选择性开启和关闭Gzip

建议使用默认值

语法gzip_http_version version 1.0|1.1
默认值gzip_http_version 1.1
位置http、server、location
6.11.gzip_min_length

针对传输数据的大小,可以选择性开启和关闭Gzip

语法gzip_min_length length
默认值gzip_min_length 20
位置http、server、location

字节bytes 千字节kb 兆m

6.12.gzip_proxied

设置是否对服务端返回的结果进行gzip压缩

语法gzip_proxied off|expired|no-cache
no store | private|no_last_modified|no_etag|auth|any
默认值gzip_proxied off;
位置http、server、location
gzip on; 
gzip_types *;
gzip_comp_level 6;
gzip_min_length 1024;
gzip_buffers 4 1024;
gzip_http_version 1.1;
gzip_vary on;
gzip_disable "MISE [1-6]\.";
gzip_proxied off;   

vim nginx_gzip.conf

6.13.sendfile和Gzip的共存问题

gzip_static

检查与文件同名的.gz文件,response中以gzip相关的header返回.gz文件的内容

语法gzip_static on | off always
默认值gzip_static off;
位置http、server、location

报错

nginx: [emerg] unknown directive “gzip_static” in /usr/local/nginx/conf/nginx.conf:33

nginx: configuration file /usr/local/nginx/conf/nginx.conf test failed

添加模块到Nginx

(1)查看配置参数

nginx -V

--prefix=/usr/local/nginx --sbin-path=/usr/local/nginx/sbin/nginx --modules-path=/usr/local/nginx/modules --conf-path=/usr/local/nginx/conf/nginx.conf --error-log-path=/usr/local/nginx/logs/error.log --http-log-path=/usr/local/nginx/logs/access.log --pid-path=/usr/local/nginx/logs/nginx.pid --lock-path=/usr/local/nginx/logs/nginx.lock

(2)将nginx二进制目录改名

mv nginx nginxold

(3)make clean

(4)使用./configure 配置参数

./configure --prefix=/usr/local/nginx --sbin-path=/usr/local/nginx/sbin/nginx --modules-path=/usr/local/nginx/modules --conf-path=/usr/local/nginx/conf/nginx.conf --error-log-path=/usr/local/nginx/logs/error.log --http-log-path=/usr/local/nginx/logs/access.log --pid-path=/usr/local/nginx/logs/nginx.pid --lock-path=/usr/local/nginx/logs/nginx.lock --with-http_gzip_static_module

(5)make

(6)

cd objs

cp nginx /usr/local/nginx/sbin

(7)make upgrade

使用测试

gzip promise.js

#响应标头
accept-ranges:bytes
connection:keep-alive
content-encoding:gzip
content-length:1065
content-type:application/javascript
date:Sat, 10 Aug 2024 08:03:15 GMT
etag:"66b71e2a-429"
last-modified:Sat, 10 Aug 2024 08:00:42 GMT
server:nginx/1.26.1
vary:Accept-Encoding

7.静态资源的缓存处理

用来减少等待数据的时间

客户端缓存

  • 浏览器缓存

服务端缓存

  • nginx /Redis / Memcached等

7.1浏览器缓存的执行流程

header说明
Expires缓存过期的日期和时间
Cache-Control设置和缓存相关的配置信息
Last-Modified设置请求资源的最后修改时间
ETag请求变量的实体标签的当前值,比如文件的MD5值

7.2expires指令

控制页面缓存

语法expires [modified] time
expires epoch |max | off
默认值expires off;
位置http、server、location

time:可以是正数也可以是为负数,指定过期时间,负数则Cache-Control为no-cache,则Cache-control的值为max-age=time

epoch:指定为1970年,Cache-control的值为no-cache

max:指定2037年,Cache-control的值为10年

off:默认不缓存

location ~ .*\.(html|js|css|png)${
	expires 1000;     //1000秒
}

7.3add_header指令

添加指定的响应头和响应值

语法add_headername value [always]
默认值----
位置http、server、location
Cache-control: must-revalidate 可缓存但必须再向源服务器进行确认
Cache-control: no-cache     缓存前必须确认其有效性
Cache-control: no-store		不缓存请求或响应的任何内容
Cache-control: no-transform		代理不可更改媒体类型
Cache-control: public	可向任意方提供响应的缓存
Cache-control: private	仅向特定用户返回响应
Cache-control: proxy-revalidate		要求中间缓存服务器对缓存的响应有效性再次确认
Cache-Control: max-age=<seconds>	响应最大Age值
Cache-control: s-maxage=<seconds>	公共缓存服务器响应的最大Age值

8.Nginx的跨域问题解决

8.1跨域问题

服务器的同源策略:浏览器最基本最核心的安全功能,如果浏览器少了同源协议,则浏览器的正常功能会收到影响

协议,域名,端口相同

语法add_headername value [always]
默认值----
位置http、server、location

Access-Control-Allow-origin 允许跨域访问的源地址信息 *

Access-Control-Allow-Methods 允许跨域请求的请求方式 GET POST

location /get{
	add_header Access-Control-Allow-Origin http:192.168.200.133;
	add_header Access-Control-Allow-Methods GET,POST,DELETE,PUT
}

8.2静态资源防盗链

HTTP头信息Referer,当浏览器向Web服务器发送请求的时候,一般都会带上Referer,来告诉浏览器是从哪个页面链接过来的

valid_referers:nginx会通过查看referer自动和valid_referers后面的内容进行匹配,如果匹配到了将 i n v a l i d r e f e r e r 变量置为 0 , 如果没有匹配到,则将 invalid_referer变量置为0,如果没有匹配到,则将 invalidreferer变量置为0,如果没有匹配到,则将invalid_referer变量置为1

语法valid_referers none | blobked | server_names | string
默认值----
位置server、location

none 如果Header中的Referer为空,允许访问

blobked:在Header中的Referer不为空

server_names:指定域名和ip

string:支持正则表达式和带*的字符串

9.url重写(Rewrite)

Rewrite,依赖PCRE的支持

ngx_http_rewrite_module

9.1set

语法set $variable value
默认值----
位置server、location、if
    server {
        listen 8080;
        server_name localhost;
        location /server{
            //定义
            set $name "test";
            set $age 18;
            default_type text/plain;
            //使用
            return 200 $name=$age;
        }
    }
$args

变量中存放了请求URL中的请求参数。比如http://192.168.200.133/server?arg1=value1&args2=value2中 的"arg1=value1&arg2=value2",功能和$query_string一样。

$http_user_agent

变量存储的是用户访问服务的代理信息(如果通过浏览器访问,记录的是浏览器的相关版本信息)

$host

变量存储的是访问服务器的server_name值

$document_uri

变量存储的是当前访问地址的URI。比如http://192.168.200.133/server?id=10&name=zhangsan中的"/server",功能和$uri一样

$document_root

变量存储的是当前请求对应location的root值,如果未设置,默认指向Nginx自带html目录所在位置

$content_length

变量存储的是请求头中的Content-Length的值

$content_type

变量存储的是请求头中的Content-Type的值

$http_cookie

变量存储的是客户端的cookie信息,可以通过add_header Set-Cookie'cookieName=cookieValue'来添加cookie数据

$limit_rate

变量中存储的是Nginx服务器对网络连接速率的限制,也就是Nginx配置中对limit_rate指令设置的值,默认是0,不限制。

$remote_addr

变量中存储的是客户端的IP地址

$remote_port

变量中存储了客户端与服务端建立连接的端口号

$remote_user

变量中存储了客户端的用户名,需要有认证模块才能获取

$scheme

变量中存储了访问协议

$server_addr

变量中存储了服务端的地址

$server_name

变量中存储了客户端请求到达的服务器的名称

$server_port

变量中存储了客户端请求到达服务器的端口号

$server_protocol

变量中存储了客户端请求协议的版本,比如"HTTP/1.1"

$request_body_file

变量中存储了发给后端服务器的本地文件资源的名称

$request_method

变量中存储了客户端的请求方式,比如"GET","POST"等

$request_filename

变量中存储了当前请求的资源文件的路径名

$request_uri

变量中存储了当前请求的URI,并且携带请求参数,比如http://192.168.200.133/server?id=10&name=zhangsan中的"/server?
 log_format main '$remote_addr-$request - $status - $request_uri - $http_user_agent';
    server {
        listen 8080;
        server_name localhost;
        location /server{
            set $name "test";
            set $age 18;
            default_type text/plain;
            return 200 $name=$age;
        }


192.168.3.1 - - [11/Aug/2024:02:53:25 -0400] "GET /server HTTP/1.1" 200 7 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36"

9.2if指令

条件判断

if (){

}

语法if (condition)
默认值----
位置server、locatio

空字符串和0为false,其他都为true

使用=和!=来比较字符串是否相等

字符串不需要添加引号

~正则匹配 ~*不区分大小写

if ($http_user_agent ~ MSIE){
		#$http_user_agent是否包含MISE,如果包含返回true
}

-f指定文件是否存在
if (!-f $request_file){

}

目录-d

请求的目录或文件-e

是否可执行-x

9.3break指令

语法break
默认值----
位置server、locatio

终止此次操作并重定向操作

9.4return

用于完成对请求的处理,直接向客户端返回,return后所有的nginx配置都是无效的

语法return code [text]
return code URL
return html
默认值----
位置server、locatio、if

9.5rewrite

语法rewrite regex replacement [flag]
默认值----
位置server、locatio、if

regex:用来匹配URI的正则表达式

匹配成功后,用于替换URI的内容,如果是http或https开头则不会继续向下匹配

location /rewrite{
	rewrite ^/rewrite/(test)\w*$ /$1;
}

//访问http://ip/rewrite/testabc         ------->    /test

flag:用来设置rewrite对uri的处理行为,可选值如下

  • last:作为一个新的uri,可以使用其他的location块进行处理
location /rewrite{
	rewrite ^/rewrite/(test)\w*$ /$1 last;
}
  • break:作为一个新的uri,将重写的uri在本location中继续处理,不会将新的uri转向其他的location块
location /rewrite{
	rewrite ^/rewrite/(test)\w*$ /$1 break;
}
  • redirect:指明为重定向,状态码为302
location /rewrite{
	rewrite ^/rewrite/(test)\w*$ /$1 redirect;
}
  • permanent:状态码为301,指明为永久重定向
location /rewrite{
	rewrite ^/rewrite/(test)\w*$ /$1 permanent;
}

9.6rewrite_log

该指令配置是否开启URL重写日志的输出功能

语法rewrite_log regex on|off
默认值----
位置http、server、locatio、if
rewrite_log on;
err_log logs_error.log notice;

9.7域名镜像

指将相同的网站分别放置在不同的服务器上,并分别使用单独的URL进行访问,其中一台为主站,其余为镜像网站

server_name_in_redirect on | off

如果为on 重定向为 http://server_name:8082/目录名/;

如果为off 重定向为 http://原URL的ip地址:8082/目录名/;

9.8目录合并

搜索引擎优化(SEO)是一种利用搜索引擎的搜索规则来提高目的网站在有关搜索引擎内排名的方式

如果目录层级有5层

http://www.web.name/server/11/22/33/44/20.html

location {
	rewrite ^/server-([0-9]+)-([0-9]+)-([0-9]+)-([0-9]+)/([0-9])\.html$ /server/$1/$2/$3/$4/$5.html
}

10.Nginx代理

10.1.正向代理

location{
	listen 82;
	location / {
		resolver #设置DNS的IP 用来解析proxy_pass中的域名
		proxy_pass http://$host$request_uri;
	}
}

在客户端配置代理服务器

请添加图片描述

10.2反向代理

10.2.1proxy_pass URL
语法proxy_pass URL
默认值----
位置locatio

URL为设置的被代理的服务器地址

proxy_pass http://192.168.133.3/getid

proxy_pass http://192.168.200.146/
proxy_pass http://192.168.200.146

# 当后面没有加上/则会吧location的请求路径拼上去,加上则不会
10.2.2peoxy_set_header

更改请求头信息,然后将新的请求头信息发送到代理服务器

语法proxy_set_header field value;
默认值proxy_set_header Host $proxy_host
proxy_set_header Connecting close;
位置http、server、locatio
location / {
	proxy_pass http://192.168.200.146:8080/;
	proxy_set_header username TOM;    #使用  $http_username
}
10.2.3proxy_redirect

重置Location和Refresh的值

语法proxy_redirect redirect replacement;
proxy_redirect default;
proxy_redirect off;
默认值proxy_redirect default
位置http、server、locatio

proxy_redirect http://192.168.200.146/ http://192.168.200.133/

proxy_redirect redirect replacement;

redirect 目标Location的值

replacement:需要替换的值

proxy_redirect default

将location的uri变量作为replacement

将proxy_pass变量作为redirect进行替换

proxy_redirect off

关闭proxy_redirect的功能

10.3安全控制

安全隔离:通过代理分开客户端到服务端的连接。在方向道理之前设置防火墙,仅留一个入口供代理服务器访问

10.3.1对流量进行加密

http转换为https协议

SSL安全套接层

TLS传输层安全

http是明文传输数据,有安全问题,https是加密传输,相当于http+ssl,可以防止流量被劫持

10.3.2添加SSL支持

复制nginx二进制文件

参数
--prefix=/usr/local/nginx --sbin-path=/usr/local/nginx/sbin/nginx --modules-path=/usr/local/nginx/modules --conf-path=/usr/local/nginx/conf/nginx.conf --error-log-path=/usr/local/nginx/logs/error.log --http-log-path=/usr/local/nginx/logs/access.log --pid-path=/usr/local/nginx/logs/nginx.pid --lock-path=/usr/local/nginx/logs/nginx.lock --with-http_gzip_static_module

./configure --with-http_ssl_modules

make

将obj下的

make upgrade

10.3.3ssl
语法ssl on| off
默认值ssl off
位置http、server
server{
	listen 443 ssl
}
10.3.4ssl_certificate

指定PEM格式的证书

语法ssl_certificate file
默认值——
位置http、server
10.3.5ssl_session_cache

配置ssl回话的缓存

语法ssl_session_cache off|none [builtin[:size]][shared:name:size]
默认值ssl_session_cache none;
位置http、server

off:禁用缓存

none:禁用回话缓存

builtin:内置OpenSSL缓存,仅在一个工作进程中使用

shared:所有工作进程之间共享缓存,缓存相关的信息用name和size来指定

10.3.6ssl_session_timeout

开启回话后,设置客户端能够反复使用存储在缓存中的回话参数时间

语法ssl_session_timeout time
默认值ssl_session_timeout 5m //5分钟
位置http、server
10.2.7ssl_ciphers

指出允许的密码,为openSSL支持的格式

openssl ciphers

TLS_AES_256_GCM_SHA384:TLS_CHACHA20_POLY1305_SHA256:TLS_AES_128_GCM_SHA256:TLS_AES_128_CCM_SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES256-CCM:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-CCM:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES256-SHA:ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES128-SHA:AES256-GCM-SHA384:AES256-CCM:AES128-GCM-SHA256:AES128-CCM:AES256-SHA256:AES128-SHA256:AES256-SHA:AES128-SHA:DHE-RSA-AES256-GCM-SHA384:DHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES256-CCM:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES128-CCM:DHE-RSA-AES256-SHA256:DHE-RSA-AES128-SHA256:DHE-RSA-AES256-SHA:DHE-RSA-AES128-SHA:PSK-AES256-GCM-SHA384:PSK-CHACHA20-POLY1305:PSK-AES256-CCM:PSK-AES128-GCM-SHA256:PSK-AES128-CCM:PSK-AES256-CBC-SHA:PSK-AES128-CBC-SHA256:PSK-AES128-CBC-SHA:DHE-PSK-AES256-GCM-SHA384:DHE-PSK-CHACHA20-POLY1305:DHE-PSK-AES256-CCM:DHE-PSK-AES128-GCM-SHA256:DHE-PSK-AES128-CCM:DHE-PSK-AES256-CBC-SHA:DHE-PSK-AES128-CBC-SHA256:DHE-PSK-AES128-CBC-SHA:ECDHE-PSK-CHACHA20-POLY1305:ECDHE-PSK-AES256-CBC-SHA:ECDHE-PSK-AES128-CBC-SHA256:ECDHE-PSK-AES128-CBC-SHA
语法ssl_ciphers ciphers
默认值ssl_ciphers HIGH:!aNULL:!MD5
位置http、server
10.2.8ssl_perfer_server_ciphers on|off
语法ssl_perfer_server_ciphers on
默认值ssl_perfer_server_ciphers off
位置http、server

10.4生成证书

购买域名,购买SSL证书

openssl

确认系统是否安装openssl

openssl version

使用命令安装

mkdir /root/cert
openssl genrsa -des3 -out server.key 1024
openssl req -new -key server.key -out server.csr
cp server.key server.key.org
openssl rsa -in server.key.org -out server.key
openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt

10.5配置

server {
        listen       443 ssl;
        server_name  localhost;

        ssl_certificate      cert.pem;
        ssl_certificate_key  cert.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;
        }
    }
 #报错
 SSL_CTX_use_certificate("/root/cert/server.crt") failed (SSL: error:140AB18F:SSL routines:SSL_CTX_use_certificate:ee key too small)
nginx: configuration file /usr/local/nginx/conf/nginx.conf test failed

将大小改为2048

mkdir /root/cert
openssl genrsa -des3 -out server.key 2048
openssl req -new -key server.key -out server.csr
cp server.key server.key.org
openssl rsa -in server.key.org -out server.key
openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt

请添加图片描述

10.6方向代理的优化

10.6.1proxy_buffering

开启关闭代理服务器的缓冲区

语法proxy_buffering on | off
默认值proxy_buffering on
位置http、server、location
10.6.2proxy_buffers

单个连接读取响应的缓存区个数和大小

number个数

size大小

语法proxy_buffers number size
默认值proxy_buffers 8 4k
位置http、server、location

10.6.3proxy_buffer_size

被代理服务器获取的第一部分响应数据的大小

语法proxy_buffer_size size
默认值proxy_buffer_size 8k
位置http、server、location
10.6.4proxy_temp_path

当缓存区满之后,会被临时存放在磁盘中,设置文件路径

语法proxy_temp_path path
默认值proxy_temp_path proxy_temp
位置http、server、location
10.6.5proxy_temp_file_write size

设置磁盘缓存文件的大小

语法proxy_temp_file_write size
默认值proxy_temp_file_write 8k
位置http、server、location

11.负载均衡

将请求分配给不同的服务器中

横向扩展:提升单机的硬件

纵向扩展:提升服务器数量

11.1处理方式

用户手动选择,提供不同线路、不同服务器的链接

11.2四/七层负载均衡

OSI,开放式系统互联模型

四层负载均衡为传输层,基于IP+PORT的负载均衡

七层负载均衡指的是应用层,主要是基于虚拟的URL或主机IP的负载均衡

四层负载均衡不识别域名,七层负载均衡识别域名

实际使用模式

四层(LVS)+七层(Nginx)

11.3Nginx七层负载均衡

11.3.1upstream

定义一组服务器,监听不同端口的服务器

语法upstream name {}
默认值------
位置http
11.3.2server

指定后端服务器的名称和一些参数,可以使用域名、IP、端口或者unix-socket

语法server name [paramerters]
默认值------
位置upstream
upstream 服务名{
	server http://192.168.3.133:8080;
	server http://192.168.3.133:8081;
}

http://服务名   //访问
状态概述
down当前server暂时不参与负载均衡
backup标记为备份服务器,当主服务器不可用是,将用来传递请求
max_conns设置代理服务器同时活动链接的最大数量,默认为0
max_fails允许请求代理服务器失败的次数,默认1
fail_timeoutmax_fails后,服务暂停的时间,默认10s
11.3.3down
upstream 服务名{
	server http://192.168.3.133:8080 down;
	server http://192.168.3.133:8081;
}

11.4负载均衡策略

名称说明
轮询默认
weight权重,默认1,权重越高,被分配的请求越多
ip_hash依据ip分配,每个访客可以固定访问一个后端服务
least_conn依据最少连接方式,把请求优先分配给连接数少的后端服务器
url_hash依据url分配方式,这样相同的url会被分配到同一个后端服务
fair依据响应时间方式,响应时间短的服务将被优先分配
11.4.1轮询

轮询不需要做任何配置

按请求时间逐个分配到不同的后端服务器

11.4.2加权轮询

weight=number 默认为1,权重越大,被分配请求的概率越大

upstream webservers{
    server 192.168.100.128:8080 weight=90 ;
    server 192.168.100.129:8080 weight=10 ;
}
11.4.3ip_hash
语法ip_hash;
默认值------
位置upstream
upstream webservers{
	ip_hash;
    server 192.168.100.128:8080;
    server 192.168.100.129:8080;
}
11.4.4least_conn
upstream webservers{
	least_conn;
    server 192.168.100.128:8080;
    server 192.168.100.129:8080;
}
11.4.5url_hash

同一个url会到达同一个服务器

upstream webservers{
	hash $request_uri
    server 192.168.100.128:8080;
    server 192.168.100.129:8080;
}
11.4.6fair

下载nginx-upstream-fair

gnosek/nginx-upstream-fair: The fair load balancer module for nginx (github.com)

/root/nginx/module/fair 解压并放入

./configure --prefix=/usr/local/nginx --sbin-path=/usr/local/nginx/sbin/nginx --modules-path=/usr/local/nginx/modules --conf-path=/usr/local/nginx/conf/nginx.conf --error-log-path=/usr/local/nginx/logs/error.log --http-log-path=/usr/local/nginx/logs/access.log --pid-path=/usr/local/nginx/logs/nginx.pid --lock-path=/usr/local/nginx/logs/nginx.lock --with-http_gzip_static_module --with-http_ssl_module --add-module=/root/nginx/module/fair

make

/root/nginx/module/fair/ngx_http_upstream_fair_module.c: 在函数‘ngx_http_upstream_init_fair_rr’中:
/root/nginx/module/fair/ngx_http_upstream_fair_module.c:543:28: 错误:‘ngx_http_upstream_srv_conf_t’ {或称 ‘struct ngx_http_upstream_srv_conf_s’}没有名为‘default_port’的成员
     if (us->port == 0 && us->default_port == 0) {
                            ^~
/root/nginx/module/fair/ngx_http_upstream_fair_module.c:553:51: 错误:‘ngx_http_upstream_srv_conf_t’ {或称 ‘struct ngx_http_upstream_srv_conf_s’}没有名为‘default_port’的成员
     u.port = (in_port_t) (us->port ? us->port : us->default_port);
                                                   ^~
make[1]: *** [objs/Makefile:1254:objs/addon/fair/ngx_http_upstream_fair_module.o] 错误 1
make[1]: 离开目录“/root/nginx/core/nginx-1.26.1”
make: *** [Makefile:10:build] 错误 2

报错解决方案

cd nginx目录/src/http

vim ngx_http_upstream.h

struct ngx_http_upstream_srv_conf_s {
    ngx_http_upstream_peer_t         peer;
    void                           **srv_conf;

    ngx_array_t                     *servers;  /* ngx_http_upstream_server_t */

    ngx_uint_t                       flags;
    ngx_str_t                        host;
    u_char                          *file_name;
    ngx_uint_t                       line;
    in_port_t                        port;
    in_port_t                        default_port;
    ngx_uint_t                       no_port;  /* unsigned no_port:1 */

#if (NGX_HTTP_UPSTREAM_ZONE)
    ngx_shm_zone_t                  *shm_zone;
#endif
};

make

upstream webservers{
	fair;
    server 192.168.100.128:8080;
    server 192.168.100.129:8080;
}

11.5四层负载均衡

添加模块

--prefix=/usr/local/nginx --sbin-path=/usr/local/nginx/sbin/nginx --modules-path=/usr/local/nginx/modules --conf-path=/usr/local/nginx/conf/nginx.conf --error-log-path=/usr/local/nginx/logs/error.log --http-log-path=/usr/local/nginx/logs/access.log --pid-path=/usr/local/nginx/logs/nginx.pid --lock-path=/usr/local/nginx/logs/nginx.lock --with-http_gzip_static_module --with-http_ssl_module --add-module=/root/nginx/module/fair --with-stream
11.5.1stream指令

和http同级,指定服务器指令的配置文件上下文

语法stream;
默认值------
位置main

11.6redis

https://redis.io/downloads/#redis-downloads

tar -zxf redis.tar.gz

make PREFIX=/usr/local/redis/redis01 install

cd /usr/local/redis/redis01

vim redis.conf

  • port 6379
  • daemonize yes

启动

./redis-server …/redis.conf

bind 0.0.0.0 允许其他主机访问

redis-cli -h 192.168.3.133 -p 6379

stream{
	upstream redisbackend{
		server 192.168.3.133:6379;
		server 192.168.3.133:6378;
	}
	server{
		listen 81;
		proxy_pass redisbackend;
	}
}

11.7tomcat

tar -zxf tomcat.tar.gz

cd tomcat/bin

./startup

12.Nginx缓存集成

12.1proxy_cache_path

用于指定缓存文件的存放路径

语法proxy_cache_path path [levels=number]
keys_zone=zone_name:zone_size [inactive=time][max_size=size];
默认值------
位置http

path:缓存路径存放地址

levels:指定缓存空间对应的目录,可以设置3层。每层取1|2

232563c4a42a4c5f4234b324e273d20d

levels=1:2 缓存空间有两层,第一次一个字母,第二次两个

levels=1:2 /usr/local/proxy_cache/d/20

levels=1:2:2 /usr/local/proxy_cache/d/20/d3

keys_zone 指定名称和大小

keys_zone=itcast:200m

inactive:指定缓存数据多长时间未被访问就会删除

inactive=1d 1天没被访问就会删除

max_size设置最大缓存空间

max_size=20g

proxy_cache_path /usr/local/proxy_cache levels=1:2 keys_zone=richu:200m inactive=1d max_size=20g;

12.2proxy_cache

开启关闭代理缓存

语法proxy_cache off | on
默认值proxy_cache off
位置http、server、location

12.4proxy_cache_key

设置web缓存的key值,Nginx会根据key值MD5哈希缓存

语法proxy_cache_key key
默认值proxy_cache_key s c h e m e scheme schemeproxy_host$request_uri
位置http、server、location

12.5proxy_cache_valid

不同状态码的URL设置不同的缓存时间

proxy_cache_valid 200 302 10m;

proxy_cache_valid 404 1m;

proxy_cache_valid any 1m;

200 302 缓存十分钟 404缓存1分钟

12.6proxy_cache_min_uses

设置资源被访问多少次之后被缓存

语法proxy_cache_min_uses number;
默认值proxy_cache_min_uses 1
位置http、server、location

12.7proxy_cache_method

缓存哪些http方法

语法proxy_cache_method GET|HEAD|POST
默认值proxy_cache_method GET HEAD;
位置http、server、location

12.8Nginx缓存的清除

1删除资源文件夹

rm -rf /usr/local/proxy_cache

2安装第三方模块

tar -zxf ngx_cache_purge-2.3.tar.gz

mv ngx_cache_purge-2.3 purge

--prefix=/usr/local/nginx --sbin-path=/usr/local/nginx/sbin/nginx --modules-path=/usr/local/nginx/modules --conf-path=/usr/local/nginx/conf/nginx.conf --error-log-path=/usr/local/nginx/logs/error.log --http-log-path=/usr/local/nginx/logs/access.log --pid-path=/usr/local/nginx/logs/nginx.pid --lock-path=/usr/local/nginx/logs/nginx.lock --with-http_gzip_static_module --with-http_ssl_module --add-module=/root/nginx/module/fair --with-stream
./configure --prefix=/usr/local/nginx --sbin-path=/usr/local/nginx/sbin/nginx --modules-path=/usr/local/nginx/modules --conf-path=/usr/local/nginx/conf/nginx.conf --error-log-path=/usr/local/nginx/logs/error.log --http-log-path=/usr/local/nginx/logs/access.log --pid-path=/usr/local/nginx/logs/nginx.pid --lock-path=/usr/local/nginx/logs/nginx.lock --with-http_gzip_static_module --with-http_ssl_module --add-module=/root/nginx/module/fair --with-stream --add-module=/root/nginx/module/purge 

make

mv nginx nginxold

cp nginx /usr/local/nginx/sbin

make upgrade

12.9使用Nginx缓存的清除

location ~ /purge(/.*) {
	proxy_cache_purge richu(proxy_cache指定的名称) richu(proxy_cache_key指定的名称)
}

13.设置资源不缓存

13.1proxy_no_cache

指定不缓存的条件

语法proxy_no_cache string …;
默认值-----
位置http、server、location

13.2proxy_caxhe_bypass

不从缓存中获取数据

语法proxy_caxhe_bypass string;
默认值-----
位置http、server、location

只要有1个不为0或不为非空则成立

13.3变量名

$cookie_nocache 当前请求中的cookie中键为nocache对应的值

$arg_nocache $arg_comment 当前请求中的参数中属性名为nocache,comment对应的值

13.4动静分离

动:后台应用程序的业务处理

静:网站的静态资源(html,javascript,css,Images等文件)

打包war放入tomcat的webapps目录下

14KeepAlive的安装

14.1配置安装

1.下载

Keepalived for Linux

2.解压缩

tar -zxf keepalives.tar.gz

3.配置

./configure --sysconf=/etc --prefix=/usr/local

4.编译安装

make && make install

/etc/keepalived/keepalived.conf文件 配置文件

/usr/local/sbin 二进制启动文件

2.配置文件

global_defs {
   notification_email {       #出问题会给下面的邮件发送消息
     acassen@firewall.loc
     failover@firewall.loc
     sysadmin@firewall.loc
   }
   notification_email_from Alexandre.Cassen@firewall.loc  #从哪个邮件发送消息
   smtp_server 192.168.200.1
   smtp_connect_timeout 30
   router_id LVS_DEVEL       #唯一标识
   vrrp_skip_check_adv_addr
   vrrp_strict
   vrrp_garp_interval 0
   vrrp_gna_interval 0
}


vrrp_instance VI_1 {
    state MASTER	#主
    interface eth0   #网卡名称
    virtual_router_id 51    
    priority 100   #指定优先级
    advert_int 1    #发送健康状况的时间间隔
    authentication {
        auth_type PASS
        auth_pass 1111
    }
    virtual_ipaddress {
        192.168.200.16
        192.168.200.17
        192.168.200.18
    }

14.2vrrp_script

自动判断nginx服务的状况

1.keepalived配置文件

vrrp_scipt 脚本名称
{
	script "脚本位置"
	interval 3 #执行时间间隔
	weight -20 #动态调整vrrp_instance的优先级
}
#!/bin/bash
num=`ps -C nginx --no-header | wc -l`
if [$num -eq 0];then
/usr/local/nginx/sbin/nginx
sleep 2
if [`ps -C nginx --no-header | wc -l ` -eq 0];then
 	kill keepalived
  fi
fi

15.使用Nginx制作下载站点

ngx_http_autoindex_module模块

(1)autoindex:启用或禁用目录列表输出

语法autoindex on|off
默认值autoindex off
位置http、server、location

(2)autoindex_exact_size:对应HTML格式,指定是否在目录列表展示文件的详细大小

语法autoindex_exact_size on | off
默认值autoindex_exact_size on
位置http、server、location

(3)autoindex_format:设置目录列表的格式

语法autoindex_format html|xml|json|jsonp
默认值autoindex_format html
位置http、server、location

(4)autoindex_location:对应HTML格式,是否在目录列表上显示时间

语法autoindex_location on |off
默认值autoindex_location off
位置http、server、location
location /download{
	root /usr/local/download;
	autoindex on;
	autoindex_exact_size on;
	autoindex_format html;
	autoindex_location on;
}

16Nginx用户认证

ngx_http_auth_basic_module模块

(1)auth_basic:使用"HTTP基本认证"协议启用用户名和密码的验证

语法auth_basic on |off
默认值auth_basic off
位置http、server、location、limit_except

(2)auth_basic_user_file:指定用户名和文件所在的位置

语法auth_basic_user_file file
默认值-----
位置http、server、location、limit_except
auth_basic 'please input your password'
auth_basic_user_file htpassword

使用一个工具生成密码

yum install -y httpd-tools
htpasswd -c /usr/local/nginx/conf/htpasswd name  //生成新文件和密码
htpasswd -b /usr/local/nginx/conf/htpasswd name password  //追加密码
htpasswd -D /usr/local/nginx/conf/htpasswd name   //删除指定用户名
htpasswd -v /usr/local/nginx/conf/htpasswd name   //验证密码
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值