nginx 安装-基础模块-代理-负载均衡-https-项目必配 文档

Nginx入门

目录

Nginx基本概述

Nginx是一个开源且高性能,可靠的http web服务,代理服务、负载均衡

  • 开源:直接获取源代码
  • 高可靠:支持海量并发
  • 高性能:服务稳定
  • 轻量:占用资源少

1. 常见的http web服务

  • Http 由apache基金会
  • IIS 微软服务版
  • GWS Google开发
  • Openrestry 基于nginx+lua
  • Tengline 淘宝基于Nginx开发

2. 为什么选择Nginx

Nginx非常轻量功能模块少(源代码仅保留http与核心模块代码,其余不够核心代码会作为插件来安装)

代码模块化(易读,便于二次开发,对于开发人员非常友好)

  • Nginx技术成熟,国内公司基本大规模使用

    ​ 适用于当前主流架构趋势,微服务、云架构、之间层

    ​ 统一技术 ,降低维护成本,降低技术更新成本

  • Nginx采用Epoll网络模型,Apache采用Select模型

    ​ Select:当用户发起一次请求,select模型就会进行一次遍历扫描,从而导致性能降低

    ​ Epoll:当用户发起请求,epoll模型会直接进行处理,效率高效,并无连接限制

Nginx应用场景

  • ​ 静态服务: html | jgp | png …

  • ​ 代理服务:

    ​ 正向代理:内访外

    ​ 反向代理:外访内和负载均衡的效果是一样的,但是工作方式有区别。

  • ​ 负载均衡:

  • ​ 缓存

  • ​ 安全服务:

    ​ -访问控制:基于ip地址,基于身份认证

    ​ WAF:DDOS攻击、CC攻击、SQL注入

  • ​ 架构

    ​ LNMP (linux、nginx、mysql、php)

    ​ LNMT(linux、ngxin、mysql、tomcat)
    在这里插入图片描述

3.Nginx部署

3.1.Nginx安装方式:

  • epel源:版本低、功能少
  • 官方源:官方编译好,封装成rpm包,并提供yum源,(推荐)
  • 源代码:自己下载源代码,使用.configure/make/make install (安装复杂,费时)

3.2.安装Nginx 1.16.1(yum)

3.2.1 配置官方Nginx官方yum源
vim /etc/yum.repos.d/nginx.repo 
[nginx-stable]
name=nginx stable repo
baseurl=http://nginx.org/packages/centos/$releasever/$basearch/
gpgcheck=1
enabled=1
gpgkey=https://nginx.org/keys/nginx_signing.key
module_hotfixes=true
3.2.2 查看安装源
[root@nginx_web1 yum.repos.d]# yum list nginx
已加载插件:fastestmirror, langpacks
Loading mirror speeds from cached hostfile
base: mirrors.aliyun.com
extras: mirrors.aliyun.com
updates: mirrors.aliyun.com
可安装的软件包
nginx.x86_64  		1:1.16.1-1.el7.ngx          nginx-stabl
3.2.3 安装Nginx
[root@nginx_web1 yum.repos.d]# yum -y install nginx
[root@nginx_web1 yum.repos.d]# nginx -v				//小v查看版本号
nginx version: nginx/1.16.1
[root@nginx_web1 yum.repos.d]# nginx -V 		//大V查看版本号及安装选项
nginx version: nginx/1.16.1
built by gcc 4.8.5 20150623 (Red Hat 4.8.5-36) (GCC) 
built with OpenSSL 1.0.2k-fips  26 Jan 2017
TLS SNI support enabled
configure arguments: --prefix=/etc/nginx --sbin-path=/usr/sbin/nginx --modules-path=/usr/lib64/nginx/modules --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 --lock-path=/var/run/nginx.lock --http-client-body-temp-path=/var/cache/nginx/client_temp --http-proxy-temp-path=/var/cache/nginx/proxy_temp --http-fastcgi-temp-path=/var/cache/nginx/fastcgi_temp --http-uwsgi-temp-path=/var/cache/nginx/uwsgi_temp --http-scgi-temp-path=/var/cache/nginx/scgi_temp --user=nginx --group=nginx --with-compat --with-file-aio --with-threads --with-http_addition_module --with-http_auth_request_module --with-http_dav_module --with-http_flv_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_mp4_module --with-http_random_index_module --with-http_realip_module --with-http_secure_link_module --with-http_slice_module --with-http_ssl_module --with-http_stub_status_module --with-http_sub_module --with-http_v2_module --with-mail --with-mail_ssl_module --with-stream --with-stream_realip_module --with-stream_ssl_module --with-stream_ssl_preread_module --with-cc-opt='-O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector-strong --param=ssp-buffer-size=4 -grecord-gcc-switches -m64 -mtune=generic -fPIC' --with-ld-opt='-Wl,-z,relro -Wl,-z,now -pie'
[root@nginx_web1 yum.repos.d]# cd /usr/lib64/nginx/modules/
3.2.4 Nginx配置文件
**Nginx主配置文件**
/etc/nginx
/etc/nginx/nginx.conf
/etc/nginx/conf.d
/etc/nginx/conf.d/default.conf
**cgi、Fastcgi、Uwcgi配置文件**
/etc/nginx/fastcgi_params
/etc/nginx/fastcgi_params
/etc/nginx/scgi_params
/etc/nginx/uwsgi_params
**Nginx编码编码转换映射文件**
/etc/nginx/win-utf
/etc/nginx/koi-utf
/etc/nginx/koi-win
**http协议得Content-Type与扩展名**
/etc/nginx/mime.types
**配置系统守护进程管理器**
/usr/lib/systemd/system/nginx.service
**Nginx日志轮询,日志切割**      ******
/etc/logrotate.d/nginx
**Nginx终端管理命令**
/usr/sbin/nginx
/usr/sbin/nginx-debug
**Nginx模块目录**
/usr/lib64/nginx
/usr/lib64/nginx/modules
**Nginx默认站点目录**
/usr/share/nginx
/usr/share/nginx/html
/usr/share/nginx/html/50x.html
/usr/share/nginx/html/index.html
**Nginx帮助手册**
/usr/share/man/man8/nginx.8.gz
/usr/share/doc/nginx-1.16.1
**Nginx的缓存目录**
/var/cache/nginx
**Nginx的日志目录**
Nginx/log/nginx

3.3 问题:安装问题

问题一:如果企业之前的Nginx都是通过源码安装,这是需要我们部署新的Nginx服务器,怎么实现

​ 解法:通过Nginx -v 获得版本、通过nginx -V 获得configuration选项

问题二:选项那么多,必须要配吗,网上搜得博文选项没那么长

​ 解法:选项是根据企业需求来指定,最好按官方来实现

3.4.安装nginx 1.16.0(源代码)

3.4.1 官方下载tar包:http://nginx.org/
3.4.2 解压软件包
tar xf nginx-1.16.0.tar.gz -C /usr/src/ 
cd /usr/src/nginx-1.16.0/
useradd -s /sbin/nologin nginx -M id nginx
3.4.3 https依赖于加密池
#安装依赖。
yum install pcre pcre-devel -y
yum install openssl openssl-devel -y  #https加密用他。
3.4.4 编译安装
–prefix=/etc/nginx
–sbin-path=/usr/sbin/nginx
–modules-path=/usr/lib64/nginx/modules
–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
–lock-path=/var/run/nginx.lock
程序安装目录和路径
–http-client-body-temp-path=/var/cache/nginx/client_temp
–http-proxy-temp-path=/var/cache/nginx/proxy_temp
–http-fastcgi-temp-path=/var/cache/nginx/fastcgi_temp
–http-uwsgi-temp-path=/var/cache/nginx/uwsgi_temp
–http-scgi-temp-path=/var/cache/nginx/scgi_temp
临时缓存目录
–user=nginx
–group=nginx
设定Nginx进程启动用户和组(安全)
–with-cc-opt设置额外的参数将被添加到CFLAGS变量
–with-ld-opt设置附加的参数,链接系统库
./configure  --prefix=/application/nginx-1.16.0/ user=nginx --group=nginx --with-compat --with-file-aio --with-threads --with-http_addition_module --with-http_auth_request_module --with-http_dav_module --with-http_flv_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_mp4_module --with-http_random_index_module --with-http_realip_module --with-http_secure_link_module --with-http_slice_module --with-http_ssl_module --with-http_stub_status_module --with-http_sub_module --with-http_v2_module --with-mail --with-mail_ssl_module --with-stream --with-stream_realip_module --with-stream_ssl_module --with-stream_ssl_preread_module --with-cc-opt='-O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector-strong --param=ssp-buffer-size=4 -grecord-gcc-switches -m64 -mtune=generic -fPIC' --with-ld-opt='-Wl,-z,relro -Wl,-z,now -pie'    //模块可以查看yum安装 nginx -V 
make 
make install
ln -s /application/nginx-1.16.0/ /application/nginx
/application/nginx/sbin/nginx 
netstat -lntup|grep nginx

4.Nginx配置文件.conf

Nginx主配置文件/etc/nginx/nginx.conf是一个纯文本类型的文件,整个配置文件是以区块的形式组成。一般,每个区块以一对大括号{ }来表示开始结束

  1. CoreModule 核心模块 全局配置
  2. EventModule 事件驱动模块
  3. httpCoreModule http内核模块 局部

4.1 需了解扩展项

  • CoreModule层下可以有Event、HTTP
  • HTTP模块层允许有多个server层,server主要用于配置多个网站
  • Server层允许有多个Location,Location主要用于定义网站访问路径

4.2 CoreModule核心模块

user	nginx;				       #Nginx进程所使用的用户
worker_processes 1;				    #Nginx运行的worker进程数量(建议与cpu数量一致或auto)
error_log  /log/nginx/error.log		 #Nginx错误日志存放的路径
pid	/var/run/nginx.pid				#Nginx服务运行后产生的pid进程号

4.3 events事件模块

events	{
		worker_connectios	1024;		#每个worker进程支持最大连接数量默认1024
		use opool;				#事件驱动模块,epoll默认
}

4.4 http内核模块

vim /etc/nginx/nginx.conf
http {
	include       /etc/nginx/mime.types;    //支持的文件类型路径
	default_type  application/octet-stream;		//默认类型
	log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';    //日志文件格式
	access_log  /var/log/nginx/access.log  main;		//访问日志
	
	keepalive_timeout  65;					//长连接 超时间65秒 
	include /etc/nginx/conf.d/*.conf;		//所有配置文件路径
	}
	
[root@nginx_web1 html]# egrep -v '^$|^.*#' /etc/nginx/conf.d/default.conf  //过滤注释信息	
vim /etc/nginx/nginx/conf.d/default.conf
	server {
		listen 80;						//监听端口号80
		server_name localhost;			 //提供服务的域名或主机名
		#access_log  /var/log/nginx/host.access.log		//访问日志
		location	/	{
			 root   /usr/share/nginx/html;		//访问网站代码路径
        	  index  index.html index.htm;		//服务器返回的默认页面文件
		}
		//指定代码,统一定义错误页面,错误代码重定向到新的Location
		error_page   500 502 503 504  /50x.html;	
		    location = /50x.html {
        	 root   /usr/share/nginx/html;
    	}
	}
	
[root@nginx_web1 conf.d]# vim oldboy.conf     //多站点可以分不同文件编写。前提主机名、端口、ip不能冲突
	server {
		listen 80
		server_name www.oldboy.com
		location	/	{
				root	/oldboy/www
				index.php
		}
	}

5.Nginx配置网站

[root@nginx_web1 conf.d]# mv default.conf default.conf.bak
[root@nginx_web1 conf.d]# vim oldboy.conf
server {
	listen	80;
	server_name localhost;
	location / {
		root /html;
		index index.html;
	}
}
[root@nginx_web1 conf.d]# mkdir /html
[root@nginx_web1 conf.d]# echo "nihao123456778" > /html/index.html
[root@nginx_web1 conf.d]# nginx -t 					//检测配置文件
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
systemctl restart nginx

[root@nginx_web1 conf.d]# tail /var/log/nginx/access.log		//访问日志
[root@nginx_web1 conf.d]# tail /var/log/nginx/error.log			//错误日志信息

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-LWOfhzOT-1589107474762)(E:\Linux\老男孩文档\image\image-20200118140621039.png)]

Nginx基础模块

官方帮助信息
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-8KjiL3wu-1589107474765)(E:\Linux\老男孩文档\image\image-20200118170255730.png)]

1.Nginx目录索引

http_autoindex_module模块

1.1 语法

默认是不允许列出整个目录浏览下载

syntax: autoindex on | off;

Default: autoindex off;

Contxte: http,server,location

1.2 autoindex常用参数

  • autoindex_exact_size off; //默认为on,显示出文件的确切大小,单位bytes。 修改为off,显示出文件大概大小,单位是KB或者MB或者GB
  • autoindex_localtime on; //默认为off,显示的文件时间为GMT时间。修改为no,显示的文件时间为文件服务器时间
  • charset utf-8,gbk; // 默认中文目录乱码,解决乱码

1.3 代码使用方法

server {
        listen  80;
        server_name localhost;
        location / {
                root /html;
                autoindex on;				//开启目录索引
                autoindex_exact_size off;	//显示出文件的确切大小,单位 
                charset utf-8,gdk;			//默认中文目录乱码,解决乱码。
                autoindex_localtime on;		//显示的文件时间为文件服务器时间
                
        }
}

[root@nginx_web1 ~]# nginx -t 
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
[root@nginx_web1 ~]# systemctl restart nginx

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-euMfgLFZ-1589107474768)(E:\Linux\老男孩文档\image\image-20200118175609311.png)]

2.Nginx状态监控status

ngx_http_stub_status_module模块提供对基本状态信息的访问。http_stub_status_module模块

2.1 语法

Syntax:stub_status
Default:
Context:server, location

2.2 代码使用方法

vim /etc/nginx/conf.d/default.conf
location	/nginx_status {
		stub_status;
		access_log off;
}

[root@nginx_web1 ~]# nginx -t 
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
[root@nginx_web1 ~]# systemctl reload nginx

2.3 测试

浏览器访问 http://ip/站点目录

Active connections: 2 		//当前连接数量
server accepts handled requests
 		166 	166 	160 
 accepts	#连接总数
 handled	#连接成功总数
 requests	#已处理的连接总数
 
Reading: 0 Writing: 1 Waiting: 1 
Reading		#nginx正在读取请求标头的当前连接数。
Writing		#nginx正在将响应写回到客户端的当前连接数。
Waiting		#当前等待请求的空闲客户端连接数。

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-cGqnKEar-1589107474770)(E:\Linux\老男孩文档\image\image-20200119165551634.png)]

3 Nginx访问控制

基于ip的访问控制 http_access_module模块
基于用户登录认证 http_auth_basic_module模块

3.1 Nginx基于ip访问控制

使用模块 http_access_module

3.1.1 允许配置语法

syntax: allow address | CIDR | unix: all;
Default: -
Context:http, server, location, limiti_except

3.1.2 拒绝配置语法

syntax: allow address | CIDR | unix: all;
Default: -
Context:http, server, location, limiti_except

3.1.3 代码使用方法

先写允许,默认拒绝所有;先写拒绝,默认允许所有。

访问控制配置示例,拒绝指定的IP,其他全部允许
vim /etc/nginx/conf.d/default.conf
location	/ {
		root /html;
		deny 192.168.1.1;
		deny 192.168.1.0/24;
		allow all;
}

访问控制配置示例,只允许谁能访问,其他全部拒绝
location	/ {
		root /html;
		allow 192.168.1.1;
		allow 192.168.1.0/24;
		deny all;
}
[root@nginx_web1 ~]# nginx -t 
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
[root@nginx_web1 ~]# systemctl reload nginx
3.1.4 测试

在这里插入图片描述

3.2 基于用户认证的访问

使用模块:http_auth_basic_module

3.2.1 配置语法
Syntax:auth_basic string | off;
Default:auth_basic off;
Context:http, server, location, limit_except
Syntax:auth_basic_user_file file;
Default:
Context:http, server, location, limit_except
3.2.2需要安装依赖组建
[root@nginx_web1 ~]# yum -y install httpd-tools
[root@nginx_web1 ~]# htpasswd  -b  -c  /etc/nginx/.auth_conf(file)  oldboy(user) 12345(password)				//创建用户名
3.2.3 代码使用方法
vim /etc/nginx/conf.d/default.conf
server {
        listen 81;
        server_name localhost;
        location / {
                root /html;
                auth_basic "Please enter your username and password";	//添加描述信息
                auth_basic_user_file /etc/nginx/.auth_conf;	//指定认证文件路径
        }
3.2.4 测试

在这里插入图片描述

4 Nginx访问限制

经常会遇到这种情况,服务器流量异常,负载过大等等,对于流量恶意的攻击访问,会带来带宽的浪费,服务器压力,影响业务,往往考虑到对同一个ip的连接数,并发数进行限制。

ngx_http_limit_conn_module模块可以根据一定的key来限制每个键值的连接数,如同一个IP来源的连接数

limit_conn_module 连接频率限制
limit_req_module 请求频率限制
http协议的连接与请求

HTTP是建立在TCP上,完成HTTP请求需要先建立TCP三次握手(称为TCP连接),再连接的基础上HTTP请求

HTTP请求建立在一次TCP连接基础上,一次TCP请求至少产生一次HTTP请求。

变量:
$binary_remote_addr 变量的长度是固定的4字节
$remote_addr 变量的长度是7-15字节

IP个ip地址32bit=4字节

4.1 Nginx连接限制语法

Syntax:limit_conn_zone key zone=name:size;
Default:–
Context:http
Syntax:limit_conn zone number;
Default:-
Context:http, server, location

4.2 代码使用方法

Nginx 连接限制实践
http {
//http段配置连接显示,同一时刻只允许一个客户端IP连接
limit_conn_zone $binary_remote_addr zone=conn_zone:10m;
......
		server	{
......
					location	/ {
.....
						limit_conn conn_zone 1;	 //同一时刻只允许一个客户端ip连接
		}
}
Nginx请求限制实战
http	{
//http段配置请求限制,rate限制速率,限制一秒钟最多一个ip请求
limit_req_zone $binary_remote_addr zone=req_game:10m  rate=1r/s;	
.....
	server {	
	......
			location  / 	{
			//1r/s只接受一个请求,,其余请求决绝并返回错误代码给客户端
					#limit_req zone=req_game;		
			//请求超过1r/s,剩下的将被延迟处理,请求数超过burst定义的数量,多余的请求返回503
					limit_req zone=req_game burst=3 nodelay;
			}
	}
}

4.3 压力测试

使用ab工具进行压力测试

yum install -y httpd-tools
[root@nginx_web1 ~]# ab -n 50 -c 20 http://127.0.0.1/index.html

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-QwyX49hp-1589107474776)(E:\Linux\老男孩文档\image\image-20200120144731329.png)]

4.4 Nginx连接限制没有请求限制有效

我们前面说的,多个请求可以建立再一次tcp连接之上,那么我们对请求的精准度,当然比对一个链接限制会更加有效,因为同一时刻只允许一个连接请求进入,但是同一时刻多个请求可以通过一个连接进入。所以我们请求限制是比较优的解决方案。

5 Nginx日志配置

ELK
​ Nginx Java json

192.168.104.143 - - [20/Jan/2020:13:58:02 +0800] “GET /%E8%85%BE%E8%AE%AF%E9%A6%96%E9%A1%B5_files/default_b.png HTTP/1.1” 200 10392 “http://192.168.101.82/” “Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36” “-”

Nginx有非常灵活的日志记录模式,每个级别的配置可以有各自独立的访问日志,日志格式 通过log_format命令自定义格式。

5.1 log_format指令

#配置语法:包括: error.log access.log
Syntax: log_format name [escape=default | json ] string …;
Default: log_format combined “…”;
Context: http

5.2 默认nginx定义语法

log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                  '$status $body_bytes_sent "$http_referer" '
                  '"$http_user_agent" "$http_x_forwarded_for"';

nginx日志格式允许包含的变量

  • $remote_addr 记录客户端IP地址
  • $remote_user 记录客户端用户名
  • $time_local 记录通用本地时间
  • $time_iso8601 记录ISO8601标准格式下的本地时间
  • $request 记录请求的方法以及请求的http协议
  • $status 记录请求的状态码(用户定位错误信息)
  • $body_bytes_sent 发送给客户端的总字节数,不包含响应头的大小
  • $bytes_sent 发送给客户端的总字节数
  • $msec 日志写入时间,单位为秒,精度是毫秒
  • $http_referer 记录从那个页面链接访问过来的
  • $http_user_agent 记录客户端浏览器相关信息
  • $http_x_forwarded_for 记录客户端ip地址
  • $request_length 请求的长度
  • $request_time 请求花费的时间,单位为秒,精度毫秒

注意:

如果Nginx位于负载均衡器,nginx反向代理后,web服务器无法直接获取客户端真是ip地址。
$remote_addr获取的是反向代理的ip地址。反向代理服务器在转发请求http头信息中
增加x+Forwarded_For信息,用来记录客户端ip地址和客户端请求的服务器地址

5.3 access_log使用方法

http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;  
log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                  '$status $body_bytes_sent "$http_referer" '
                  '"$http_user_agent" "$http_x_forwarded_for"';

# access_log  /var/log/nginx/access.log  main;
server {
        listen       80;
        server_name  localhost;
        access_log  logs/host.access.log  main;       //存放日志文件,并调用main日志格式
        location / {
            root   html;
            index  index.html index.htm;
        }
}

5.Nginx虚拟站点

环境:在一台服务器上实现多个站点

5.1 实现虚拟主机的方式

  • 基于IP:不同的IP
  • 基于端口:相同IP,不同的端口
  • 基于域名:相同的IP,相同的端口,不同的域名
基于域名:相同的IP,相同的端口,不同的域名
charset utf-8;
server {
        listen 80;
        server_name baidu.yan.com;					//baidu是主机域
        location / {
                root /html/baidu;
                index index.html;
                access_log /var/log/nginx/baidu.access.log main;
        }
        location /baidu_status {
                stub_status;
        }
}
server {
        listen 80;
        server_name jingdong.yan.com;			//京东是主机域
        location / {
                root /html/jingdong;
                index index.html;
                access_log /var/log/nginx/jingdong.access.log main;
        }
}

#修改本地host文件
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-xUCaubjP-1589107474779)(E:\Linux\老男孩文档\image\image-20200120223540575.png)]

6 NginxLocation

使用Nginx Location可以控制访问网站路径

6.1 Location语法优先级排列

匹配符匹配规则优先级
=精确匹配1
^~以某个字符串开头2
~区分大小写的正则匹配 **3
~*不区分大小写的正则匹配 **4
~!区分大小写不匹配的正则5
!~*不区分大小写不匹配的正则6
/通用匹配,任何请求都会匹配到 **7

6.2 配置网站验证location优先级

server {
        listen 88;
        server_name localhost;
        location / {
                default_type /test/html;
                index index.html;
                return 200  "location /";
                }
    	location = / {
           default_type /test/html;
            index index.html;
            return 200 "location = /";
            }
    	location ~ / {
            default_type /test/html;
            return 200 "location ~ /";
            }
    }

6.3 Location 应用场景

#通用匹配,任何请求都会匹配到
location 	/	{
	}

#严格区分大小写,匹配以.php结尾的都走这个location
location	~	\ .php$  {
		fastcgi_pass http://127.0.0.1:9000
	}

#严格区分大小写,匹配.jsp结尾的都走location
location ~ \ .jsp$ {
	porxy_pass http://127.0.0.1:8080;
}

#不区分大小写匹配,只要用户访问.jpg.gif.png,js,css都走这条location
location	~* 	.*\ .(jgp|gif|png|js|css)$	{
		rewrite	(.*) http://cdn.odlboyedu.com$request_uri;
}s

#不区分大小写匹配
location ~* "\ .(sql|bak|tgz|tar.gz)$" {
	default_type text/html;
	return 403 "启用访问控制成功"
}

在这里插入图片描述

Nginx代理

1.代理的概念

​ 中介、中间人

2.代理的实现方式

​ 正向代理
​ 内网到公网

​ 反向代理
​ 外网到内网

nginx作为代理服务器可以实现很多协议的代理,如http、IMAP\POP https。

3.代理配置参数

3.1.添加发往后端服务器的请求头信息

Syntax:proxy_set_header field value;
Default: proxy_set_header Host $proxy_host;
​ proxy_set_header Connection close;
Context:http,server,location

#用户请求的时候HOST的值是www.oldboy.com,那么代理服务器会像后端传递请求的还是www.oldboy.com。proxy_set_header Host $http_Host;

#将$remote_addr的值放进变量X-Real-IP中,$remote_addr的值为客户端的ip proxt_set_header X-Real-ip $remote_addr;

#客户端通过代理服务器访问后端服务,后端服务通过该变量会记录真是客户端地址 proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

3.2.代理到后端的TCP连接、响应等超时时间

//nginx代理与后端服务器连接超时时间(代理连接超时)

Syntax:proxy_connect_timeout time;

Default:proxy_connect_timeout 60s;

Context:http,server,location

//nginx代理等待后端服务器的响应时间

Syntax:proxy_read_timeout time;

Default:proxy_read_timeout 60s;

Context:http,server,location

//后端服务器数据回传给nginx代理超时时间

Syntax:porxy_send_timeout time;

Default:proxy_send_timeout 60s;

Context:http,server,location

3.3.proxy_buffer代理缓存区

//nginx会把后端返回内容放到缓存区当中,然后在返回给客户端,边收边传,不是全部接收在传给客户端

Syntax:proxy_buffering on | off;

Default:proxy_buffering on;

Context:http , server , location

//设置nginx代理保存用户信息的缓存区

Syntax:proxy_buffer_size size;

Default:proxy_buffer_size 4k|8k;

Context:http , server , location

//proxy_buffers 缓存区

Syntax:proxy_buffers number size;

Default:proxy_buffers 8 4k|8k;

Context:http , server , location

3.4.proxy代理网站常用配置如下,将配置写入新文件,调用使用include引用即可

[root@bl01 nginx]# cat proxy_params 
#请求头部
	proxy_set_header Host $http_host; 
	proxy_set_header X-Real-IP $remote_addr;
	proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

#超时时间
	#nginx代理与后端服务器连接超时时间(代理超时30秒)
	proxy_connect_timeout 30;  
	#nginx代理等待后端服务器的响应时间60s
	proxy_send_timeout 60; 
	# 后端服务器数据回传给nginx代理超时时间60s
	proxy_read_timeout 60;

#缓存的配置
	proxy_buffering on;
	proxy_buffer_size 32k;
	proxy_buffers 4 128k;

4.实际操作

web01操作

[root@web01 conf.d]# cat wordpress.conf 
server {
	listen 80;
	server_name yan.wordpress.com;
	root /html/wordpress;
	index index.php index.html;
	access_log /html/wordpress/log/access.log;
	error_log /html/wordpress/log/error.log;
	location ~ \.php$ { 
		root /html/wordpress;
		index index.php index.html;
		fastcgi_pass   127.0.0.1:9000;
		fastcgi_index  index.php;
		fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
		include        fastcgi_params;
}
}
[root@bl01 conf.d]# systemctl restart nginx

LB代理操作

[root@bl01 nginx]# cat proxy_params 
#请求头部
	proxy_set_header Host $http_host; 
	proxy_set_header X-Real-IP $remote_addr;
	proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

#超时时间
	#nginx代理与后端服务器连接超时时间(代理超时30秒)
	proxy_connect_timeout 30;  
	#nginx代理等待后端服务器的响应时间60s
	proxy_send_timeout 60; 
	#后端服务器数据回传给nginx代理超时时间60s
	proxy_read_timeout 60; 

#缓存的配置
	proxy_buffering on;
	proxy_buffer_size 32k;
	proxy_buffers 4 128k;

[root@bl01 conf.d]# cat wordpress_proxy.conf 
	server {
		listen 80;
		server_name yan.wordpress.com;
		location / {
			proxy_pass http://172.168.20.6:80;
			include proxy_params;
		}
	}
[root@bl01 conf.d]# systemctl restart nginx   重启会清空缓存

5.排错

如果通过代理访问不到web页面,怎么排错。

  1. 检查web服务器是否能提供服务,

    ​ 检查配置文件

    ​ 根据日志判断错误类型

    ​ 网页也目录、索引页是否创建,权限

    ​ 服务是否启动

  2. 检查代理服务器的配置

    ​ 检查配置文件

Nginx负载均衡

web服务器,直接面向用户,往往要承载大量并发请求,单台服务器难以负荷,我使用WEB服务器集群,前端使用Nginx负载均衡,将请求分散到打到我们后端服务器集群中,实现负载均衡的分发。那么会大大提升系统的吞吐率,请求性能、高容灾。

LB load balance
SLB server lb
在这里插入图片描述

1.Nginx负载均衡按层划分

1.2负载均衡按层划分应用场景:

1.2.1.四层负载均衡

​ IP地址
​ TCP/UDP
​ 端口号

1.2.2.七层负载均衡

​ HTTP
​ HTTPS
​ FTP
​ SMTP

2.Nginx负载均衡配置场景

Nginx实现负载均衡需要用到proxy_pass代理模块配置。

Nginx负载均衡是将客户端请求代理转发至一组upstream虚拟服务池

3.Nginx upstream配置语法

Syntax:upstream name {…}

Default:–

Context:http

//upstream 例子

upstream backend {
	server backend1.example.com weight=5;
	server backend2.example.com:8080;
	server unix:/tmp/backend3;
	server backend1.example.com:8080 backup;
	}
server {
		location / {
				proxy_pass http://backend;	
		}	
}

4.环境规划实验7层

角色外网内网主机名
LB1ens33:192.168.154.41ens32:172.168.20.12bl01
web1192.168.154.132172.168.20.6web01
web2192.168.154.133172.168.20.7web02

4.1.web1配置

[root@web01 www1]# echo "hellow 172.168.20.6" > index.html

[root@web01 www1]# cat /etc/nginx/conf.d/www1.conf 
server {
	listen 80;
	server_name yan.www.com;
	access_log /html/www1/log/access.log;
	error_log /html/www1/log/error.log;
	location / {
		root /html/www1/;
		index index.html;
	}
}

[root@web01 www1]# systemctl reload nginx

4.2.web02配置

[root@web02 www1]# echo "hellow 172.168.20.7" > index.html

[root@web01 www1]# cat /etc/nginx/conf.d/www1.conf 
server {
	listen 80;
	server_name yan.www.com;
	access_log /html/www1/log/access.log;
	error_log /html/www1/log/error.log;
	location / {
		root /html/www1/;
		index index.html;
	}
}

[root@web02 www1]# systemctl reload nginx

4.3.LB01 配置

[root@bl01 nginx]# cat proxy_params 
proxy_set_header Host $http_host; 
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_connect_timeout 30; 
proxy_send_timeout 60;
proxy_read_timeout 60;
proxy_buffering on;
proxy_buffer_size 32k;
proxy_buffers 4 128k;

[root@bl01 conf.d]# cat upstream.conf 
upstream web {					#创建及群组
	server 172.168.20.6;
	server 172.168.20.7;
}
server {
	listen 80;
	server_name yan.www.com;
	location / {
		proxy_pass http://web;
		include proxy_params;		#调用及群组
	}
}

[root@bl01 conf.d]# systemctl restart nginx

4.4.验证

使用浏览器访问yan.www.com,然后不断刷新测试

5.Nginx负载均衡后端服务器状态

后端web服务器在前端Nginx负载调度器中的状态

状态概述
down当前的server展示不参与负载均衡
backup预留的备份服务器
max_fails允许请求失败的次数
fail_timeout经过max_fails失败后,服务服务暂停时间
max_conns限制最大接受连接数

测试案例:

1.测试down状态,测试该server不参与负载均衡的调度

upstream load_pass {

	server 172.168.20.6 down;

	}

2.测试backup及down状态
upstream load_pass {
	server 172.168.20.6 down;
	server 172.168.20.7 backup;
    server 172.168.20.6 max_fails=1 fail_timeout=2s;
	}
location / {
	proxy_pass http://load_pass;
	include proxy_params;
	}

3.测试max_fail失败次数和fail_timeout多少次则标记down

upstream load_pass {
		server 172.168.20.6;
        server 172.168.20.7 max_fail=2 fail_timeout=10s;
}

4.测试max_conns最大TCP连接数

upstream load_pass {
		server 172.168.20.6;
		server 172.168.20.7 max_conns=1;
}

6.Nginx负载均衡调度算法

调度算法概述
轮询按时间寻内需逐一分配后端服务器默认(rr)
weight加权轮询,weight值越大,分配道德访问几率越高(wrr)
ip_hash每个请求按访问ip的hash结果分配,这样来自同一个ip地址固定访问后端服务器
url_hash按照访问url的hash结果来分配请求,每个URL定向到同一个后端服务器
least_conn最少连接数,那个机器连接数最少就分发(lc)
wlc加权最少连接

1.Nginx负载均衡【rr】轮询具体配置

upstream load_pass {
	server 172.168.20.6;
	server 172.168.20.7;
	}

2.均衡【weight】权重轮询具体配置

upstream load_pass {
		server 172.168.20.6 weight=5;
		server 172.168.20.7;
}

3.Nginx股灾均衡ip_hash具体配置,不能和weight一起使用。

//如果客户端走相同代理,会导致某一台服务器连接过多

upstream load_pass {
		ip_hash;
		server 172.168.20.6;
		server 172.168.20.7;
}

7.配置四层负载均衡

7.1修改主配置文件/etc/nginx/nginx.conf

[root@bl01 ~]# cat /etc/nginx/nginx.conf 
user  nginx;
worker_processes  1;

error_log  /var/log/nginx/error.log warn;
pid        /var/run/nginx.pid;

events {
    worker_connections  1024;
}
#四层代理
include /etc/nginx/conf.c/*.conf;    //添加代理目录
[root@bl01 ~]# mkdir /etc/nginx/conf.c   //创建负载配置文件目录
[root@bl01 ~]# vim /etc/nginx/conf.c/lb.conf  //配置四层负载文件
stream {
        upstream ssh_web01 {
                server 192.168.154.132:22;
        }
        upstream ssh_web02 {
                server 192.168.154.133:22;
        }
        upstream mysql_01 {
                server 192.168.154.135:3306;
        }
        server {
                listen 5555;
                proxy_pass ssh_web01;
                proxy_connect_timeout 1s;
                proxy_timeout 300s;
        }
        server {
                listen 6666;
                proxy_pass ssh_web01;
        }
        server {
                listen 33061;
                proxy_pass mysql_01;
        }
}

Nginx Rewrite(重定向)

1.什么是rewrite

Rewrite及URL重写,主要是实现地址重写,以及重定向,就是把输入Web的请求重定向到其他URL的过程

2.Rewrite使用场景

  • URL地址跳转,列入用户访问old.com将其跳转到oldboy.com,或者当用户通过http的方式访问old.com时,将其跳转至https的方式访问oldboy.com.
  • URL伪静态,将动态页面显示为静态页面的一种技术,便于搜索引擎的录入,同时减少动态URL地址对外暴露过多的参数,提升更高的安全性。
  • 搜索引擎SEO优化依赖与URL路径,以便支持搜索引擎录入。
  • 可以调整用户浏览的URL,看起来更规范,合乎开发及产品人员的要求。

3.Rewrite配置语法

示例

Syntax:rewrite regex replacement [flag];

Default:–

Context:server,location,if

4.常用正则表达式

字符描述
\将后面接着的字符标记为一个特殊字符或者一个原义字符或一个向后引用
^匹配输入字符串的起始位置
$匹配输入字符串的结束位置
*匹配前面的字符零次或者多次
+匹配前面字符串一次或者多次
?匹配前面字符串的零次或者一次
.匹配除“\n”之外的所有单个字符
(pattern)匹配括号内的pattern

5.Rewrite 标记Flag

rewrite 指令根据表达式来重定向rul,或者修改字符串。可以应用于server,location,if环境下,每行rewrite指令最后跟一个flag标记,支持的flag标记有如下表格所示:

标记符号说明
last本条规则匹配完成后继续向下匹配新的location URI规则
break本条规则匹配完成后终止,不在匹配任何规则
redirect返回302临时重定向
permanent返回301永久重定向

last与break对比总结

last

  1. last进行Rewrite匹配成功后,停止当前这个请求,并根据Rewrite匹配的规则重新向Server发起一个请求。
  2. 新请求的内容是域名+URL,对应的地址为www.lodboy.com/2017_old

break

  1. break进行Rewrite匹配成功后,不会像last重新发起请求,首先找到站目录下/clod/2017_old/默认返回页面是否存在,如不存在则404,如存在继续往下匹配。
  2. 根据Rewrite匹配的规则,跳转至www.oldboy.com/2017_old/的URL地址,匹配成功后则不继续匹配。

6.引用Nginx的全局变量

列:http://localhost:88/test1/test2/test.php

  • $host:localhost
  • $server_port: 88
  • $request_uri:/test1/test2/test.php
  • $document_uri: /test1/test2/test.php
  • $document_root: /var/www/html
  • $request_filename: /var/www/html/test1/test2/test.php

7.Rewrite匹配优先级

  • 1.执行server块的rewrite指令
  • 2.执行location匹配
  • 3.执行选定的location中的rewrite

8.开启Nginx的Rewrite 日志功能

vim /etc/nginx/nginx.conf

#1.设置nginx的错误日志级别为notice

error_log /var/log/nginx/error.log notice;

#2.在http模块层,增加一行rewrite on开启日志功能

http {
	rewrite_log on;
	server {
 .......
	}	
}

9.案例

案例一:

页面跳转到www.baidu.com

 server  {
        listen          80;
            server_name     yan.wordpress.com;
            charset     utf-8;
            root /html/wordpress;
            index index.php index.html;
        location / {
                rewrite ^/ https://www.baidu.com;	//正则匹配 到www.baidu.com
        }
        location ~ \.php$ {
            root /html/wordpress;
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
            fastcgi_pass 127.0.0.1:9000;
            include fastcgi_params;
            fastcgi_index index.php;
        }
}

systemctl restart nginx
案例二:

用户访问/abc/1.html 实际上真是访问是ccc/bbb/2.html
http://rewrite.odboy.com/abc/1.html => http://rewrite.odboy.com/ccc/bbb/2.html

[root@web02 html]# mkdir -p /ccc/bbb
[root@web02 html]# echo "bbbbbcccccc" > /ccc/bbb/2.html

[root@web02 html]# cat /etc/nginx/conf.d/rewrite.conf 
server {
	listen 80;
	server_name rewrite.oldboy.com;
	root /html;
	index index.html;
	location ~* /abc/1.html {
		rewrite /abc/1.html /ccc/bbb/2.html;
	}
}
配置优化一:
[root@web02 html]# cat /etc/nginx/conf.d/rewrite.conf 
server {
	listen 80;
	server_name rewrite.oldboy.com;
	root /html;
	index index.html;
	location ~* /abc/1.html {
		rewrite  .* /ccc/bbb/2.html;
	}
}

在这里插入图片描述

配置优化二:
[root@web02 html]# cat /etc/nginx/conf.d/rewrite.conf 

server {
        listen 80;
        server_name rewrite.oldboy.com;
        root /html;
        index index.html;
        location ~* /abc/ {
        		//这两行都是302跳转,不要一起配置。
                #rewrite .* /ccc/bbb/2.html redirect;  
                return 302 /ccc/bbb/2.html;
        }
}

在这里插入图片描述

案例三:

用户访问http://rewrite.oldboy.com/2018/ccc/bbb/2.html ==> http://rewrite.oldboy/2014/ccc/bbb/2.html

[root@web02 html]# mkdir 2014
[root@web02 html]# mv ccc 2014/
[root@web02 html]# chown -R www.www 2014/

[root@web02 html]# cat /etc/nginx/conf.d/rewrite.conf 
server {
        listen 80;
        server_name rewrite.oldboy.com;
        root /html;
        index index.html;
        location /2018 {                
			rewrite ^/2018/(.*)$ /2014/$1 redirect;   
        }       
}  
案例四:

用户访问/test目录下任何内容,实际上真实访问的是rewirte.oldboy.com

[root@web02 html]# cat /etc/nginx/conf.d/rewrite.conf 
server {
        listen 80;
        server_name rewrite.oldboy.com;
        index 2.html;
        root /html/ccc/bbb;
        location /test {
                rewrite (.*) http://rewrite.oldboy.com redirect;
        }

}

在这里插入图片描述

案例五:

#http://rewrite.oldboy.com/course-11-22-33-course_33.html ==> http://rewrite.oldboy.com/course/11/22/33/course_33.html

[root@web02 html]# mkdir -p 11/22/33
[root@web02 html]# echo "/11/22/23" > 11/22/33/course_33.html

[root@web02 html]# cat /etc/nginx/conf.d/rewrite.conf 

server {
        listen 80;
        server_name rewrite.oldboy.com;
        index 2.html;
        root /html;
        location / {
        		#灵活
                rewrite ^/(.*)-(.*)-(.*).html$ /$1/$2/$3/course_$3.html redirect;
                #固定
                rewrite ^/(.*)   /11/22/33/course_33.html redirect;
        }

}

在这里插入图片描述

案例六:

讲http请求,跳转至https

[root@web02 html]# cat /etc/nginx/conf.d/rewrite.conf 
server {
        listen 80;
        server_name rewrite.oldboy.com;
        rewrite ^(.*) https://$server_name$1 redirect;
        #return 302 https://$request_uri;
}       
server {
        listen 443;
        server_name rewrite.oldboy.com;
        ssl on
}   

Nginx HTTPS

HTTPS基本概念

1.SSL

  • 安全套接层
  • 认证用户和服务器,确保数据发送到正确的客户机和服务器
  • 加密数据以防止数据中途窃取
  • 维护数据的完整性,确保数据在传过程中不被改变

2.HTTPS

​ 使用SSL来实现安全的通信

3.证书

  • 证书用于保证密钥的合法性

  • 证书的主体可以使用户、计算机、服务等

  • 证书格式遵循X.509标准

  • 数字证书包含信息

    • 使用者的公钥值
    • 使用者标识信息(如名称和电子邮件地址)
    • 有限期(整数的有效时间)
    • 颁发者标识信息
    • 颁发者的数字签名
  • 数字证书由权威公正的第三方机构及CA签发

4.配置HTTP前期预备知识

  • HTTPS证书的选择
    • 专业版OV型证书,不显示企业名称
    • 高级版EV型证书,显示企业名称
  • HTTPS证书购买选择
    • 保护1个域名www
    • 保护5个域名 www images cdn test m
    • 通配符域名 *.oldboy.com
  • HTTPS注意事项
    • HTTPS不支持三级域名解析
    • Https持支持续费,证书到期需要重新申请进行替换
    • Https显示绿色,说明着呢个网站的URL都是https的
    • Https显示黄色,因为网站代码肿包含http的不安全连接
    • Https显示红色,证书是假的或者过期了

HTTPS证书申请

1.密钥生成过程

  • 生成key密钥
  • 生成证书签名请求文件(csr文件)
  • 生成证书签名文件(CA文件)

2.当前环境

**//openssl必须是1.0.2**

[root@web02 bbb]# openssl version
OpenSSL 1.0.2k-fips  26 Jan 2017

//nginx必须有ssl模块

[root@web02 bbb]# nginx -V

--with-http_ssl_module

[root@web02 bbb]# mkdir /etc/nginx/ssl_key -p
[root@web02 bbb]# cd /etc/nginx/ssl_key/

[root@web02 ssl_key]# openssl genrsa -idea -out server.key 2048
Enter pass phrase for server.key: 输入密码
Verifying - Enter pass phrase for server.key: 确认密码
[root@web02 ssl_key]# ll
总用量 4
-rw-r--r-- 1 root root 1747 2月  16 17:03 server.key

3.生成自签证书,同时去掉私钥的密码

[root@web02 ssl_key]# openssl req -days 46500 -x509 -sha256 -nodes -newkey rsa:2048 -keyout server.key -out server.crt

Country Name (2 letter code) [XX]:CN
State or Province Name (full name) []:BJ
Locality Name (eg, city) [Default City]:CP
Organization Name (eg, company) [Default Company Ltd]:CN
Organizational Unit Name (eg, section) []:EU^H^H
Common Name (eg, your name or your server's hostname) []:oldboy.com
Email Address []:1124740487@163.com
[root@web02 ssl_key]# ll

HTTPS配置场景

1.HTTPS配置语法

Syntax:ssl on | off;

Default:ssl off;

Context:http,server


Syntax:ssl_certificate file;

Default:–

Context:http,server


Syntax:ssl_certificate_key file;

Default:–

Context:http,server

2.配置支持Nginx支持https实例

[root@web02 conf.d]# cat ssl.conf 
server {
	listen 80;
	server_name www.https1.com;
	location / {
		rewrite .* https://$server_name;
	}
}
server {
	listen  443;
	server_name www.https1.com;
	ssl on;
	ssl_certificate ssl_key/server.crt;
	ssl_certificate_key ssl_key/server.key;

	location / {
		root /html/https;
		index index.html;
	}
	
}
[root@web02 conf.d]# mkdir /html/https
[root@web02 conf.d]# echo "https hellow " > /html/https/index.htm

3.测试访问,

由于该证书非第三方权威机构办法,而是我们自己签发的,所以浏览器警告
在这里插入图片描述

Nginx 项目必配

1.禁止ip地址访问,只允许域名访问

1、接收到ip访问或者指定域名访问时,返回500错误

server {
	listen 80;
	server_name www.oldboy.com    
}
server {
	listen 80 default_server;	#默认有优先返回
	server_name _;					#空主机头或者ip
	return 500;							#返回500错误
}

2、可以将流量集中导入到自己的网站,只要做一下跳转设置就可以

server {
		listen 80 default_server;
		return 302 https://www.oldboy.com;
}

2.Include 包含文件

一台服务器配置多个server网站,会导致nginx.conf主配置文件变得非常庞大而且可读性非常差。使用Include的是为了简化主配置文件。

3.alias与root路径匹配(虚拟目录)

alias是一个目录别名定义,root则是最上层目录定义

root配置实例

#用户访问image/db.jpg,实际上会上/code/image目录下区找db.jpg

location /image/ {
		root  /code;
}
ls /code/image/1.png
http://yan.test.com/image/1.png

alias配置实例:

#用户访问image/db.jpg,实际上会上/code/目录下区找

location /image/ {
	alias /code/;
}
ls /code/1.png

http://yan.test.com/image/1.png

4.error_page 自定义报错提示信息

 server {
        listen 80;
        server_name yan.test.com;
  		 location / {
    		root /html/tes2t;	//模拟404报错
   			index index.html;
  			proxy_pass http://1.1.1.1   //模拟500报错
    }

    error_page 404 /404.jpg;	//指定error404报错文件  
    error_page 500 502 503 504 /500.png;
    location = /404.jpg {   //通过location指定404报错页面路径
            root /etc/nginx/error;
    }
    		location = /500.png {
           root /etc/nginx/error;
    }

在这里插入图片描述

5.Try_file路径匹配,按顺序交叉文件是否存在

location / {
	try_file $uri $uri/ /index.php;
}

#1.检查用户请求的uri内容是否在本地,存在则解析

#2.将请求加/,类似于重定向处理

#3.最后交给index.php处理

**1.演示环境准备**
[root@nginx-web02 ~]#  echo "try_page" > /soft/code/index.html

echo "tomcat_Page" > /soft/app/apache-tomcat-9.0.12/webapps/Root/index.html

#启动tomcat

[root@nginx-web02 ~]#  sh ../startup.sh

**#检查tomcat端口**

[root@nginx-web02 ~]#  netstat -lnpt | grep “8080”

**2.配置web的tryfiles**

       server {
            listen 80;
            server_name yan.test.com;
            root  /soft/code/;
            index index.html;
       		location / {
                try_files $uri @java_page;
        }
        	location @java_page {
                proxy_pass http://127.0.0.1:8080;
        }
      systemctl restart nginx

**3.测试**

**默认访问结果:**

[root@nginx-web02 html]# curl http://yan.test.com/
tomcat_Page     //因为$uri匹配域名后面输入的呢容,所以当直接访问http://yan.test.com

[root@nginx-web02 html]# curl http://yan.test.com/index.html
try_page         //因为$uri匹配域名后面输入的呢容,所以当直接访问http://yan.test.com/index.html,$uri匹配/index.html,跳转到/soft/code/index.html

#将/soft/code/index.html文件删除

rm -rf /soft/code/index.html

**#发现由tomcat吐回请求**

[root@nginx-web02 test]# curl http://yan.test.com
tomcat_tr
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值