nginx学习笔记整理


b站地址–nginx

nginx笔记

nginx教程–w3c

nginx教程–菜鸟教程


1. 安装 nginx

1.1 虚拟机安装docker
# root账户登录,查看内核版本--虚拟机装的Centos7,linux 3.10内核
uname -a

# 把yum包更新到最新
yum update

# 设置yum源
yum-config-manager --add-repo http://download.docker.com/linux/centos/docker-ce.repo
yum-config-manager --add-repo http://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo

# 使用官方安装脚本自动安装
curl -fsSL https://get.docker.com/  |  sh

# 遇到问题: No Presto metadata available for docker-ce-stable
yum install docker-ce -y

# 重新 执行 Docker 安装脚本
curl -fsSL https://get.docker.com/  |  sh

# 
sudo docker version

# 启动 Docker 进程
sudo service docker start

# 验证 docker 是否安装成功并在容器中执行一个测试的镜像
sudo docker run hello-world

# ------------- 增加用户 --------------------------------
# 增加docker用户组
sudo groupadd docker
#  增加名字为 cookie  的用户
sudo gpasswd -a cookie docker
# docker 服务重启
sudo service docker restart
2.1 docker下安装nginx
#在/opt目录下创建docker_nginx目录
cd /opt
mkdir docker_nginx
#创建docker-compose.yml文件并编写下面的内容,保存退出
vim docker-compose.yml
version: '3.1'
services:
  nginx:
    restart: always
    image: daocloud.io/library/nginx:latest
    container_name: nginx
    ports:
      - 80:80

执行 docker-compose up -d

打开网址: 92.168.2.100:80



2. nginx配置文件

2.1 Nginx 配置文件和目录
/etc/nginx/nginx.conf 		核心配置文件
/etc/nginx/conf.d/default.conf 		默认http服务器配置文件

/etc/nginx/fastcgi_params 	fastcgi配置
/etc/nginx/scgi_params 		scgi配置
/etc/nginx/uwsgi_params 	uwsgi配置
/etc/nginx/mime.types 	设置HTTP协议的Content-Type与扩展名对应关系的文件
/etc/nginx/modules 		基本共享库和内核模块

/var/cache/nginx 	Nginx的缓存目录
/var/log/nginx 		Nginx的日志目录
/usr/sbin/nginx 	可执行命令
/usr/sbin/nginx-debug 	调试执行可执行命令

/usr/share/doc/nginx-1.18.0 	帮助文档
/usr/share/doc/nginx-1.18.0/COPYRIGHT 	版权声明
/usr/share/man/man8/nginx.8.gz 	手册

# 这四个文件是用来配置守护进程管理的
/usr/lib/systemd/system/nginx-debug.service
/usr/lib/systemd/system/nginx.service
/etc/sysconfig/nginx
/etc/sysconfig/nginx-debug

# 这三个文件是编码映射文件,因为作者是俄国人
/etc/nginx/koi-utf
/etc/nginx/koi-win
/etc/nginx/win-utf 	

常用命令

  • 启动nginx: service nginx start,Windows下cmd命令:start nginx.exe
  • 检查nginx配置文件是否有语法错误:nginx -t
  • 关闭nginx: nginx -s stop
  • 重启nginx: nginx -s reload
# 查看容器id
docker ps

#查看当前nginx的配置需要【进入docker容器中】
docker exec -it 容器id bash

root@37136a6bbb58:/etc/nginx# ls
conf.d	fastcgi_params	koi-utf  koi-win  mime.types  modules  nginx.conf  scgi_params	uwsgi_params  win-utf

#进入容器后
cd /etc/nginx/
cat nginx.conf
2.2 核心配置文件nginx.conf文件
user  nginx;
worker_processes  1;

error_log  /var/log/nginx/error.log warn;
pid        /var/run/nginx.pid;
# 以上为全局块
# worker_processes的数值越大,Nginx的并发能力就越强
# error_log代表Nginx错误日志存放的位置
# pid是Nginx运行的一个标识

events {
    worker_connections  1024;
}
# events块
# worker_connections的数值越大,Nginx的并发能力就越强

http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

    access_log  /var/log/nginx/access.log  main;
    sendfile        on;
    keepalive_timeout  65;
    
    #include /etc/nginx/conf.d/*.conf;
    server {
    	listen       80;
    	listen  [::]:80;
    	server_name  localhost;

   		location / {
        	root   /usr/share/nginx/html;
       		index  index.html index.htm;
    	}
    	# location块
		# root:将接受到的请求根据/usr/share/nginx/html去查找静态资源
		# index:默认去上述的路径中找到index.html或index.htm
    }
    # server块
	# listen代表Nginx监听的端口号
	# server_name代表Nginx接受请求的IP
}
# http块
# include代表引入一个外部文件
# include  /etc/nginx/mime.types;  存放着大量媒体类型---设置HTTP协议的Content-Type与扩展名对应关系的文件
#include /etc/nginx/conf.d/*.conf;	引入了conf.d下以.conf为结尾的配置文件
2.3 修改docker-compose文件
#退出容器\关闭容器
exit

# 关闭 nginx 
docker-compose down

# 修改 docker-compose.yml
vi docker-compose.yml

增加数据卷
volumes:
- /opt/docker_nginx/conf.d/:/etc/nginx/conf.d

当前/opt/docker_nginx/目录下的 conf.d 映射到 /etc/nginx 目录下的 conf.d

version: '3.1'
services: 
  nginx:
    restart: always
    image: daocloud.io/library/nginx:latest
    container_name: nginx
    ports: 
      - 80:80
    volumes:
      - /opt/docker_nginx/conf.d/:/etc/nginx/conf.d
#重新构建容器
docker-compose bulid
#重新启动容器
docker-compose up -d

这时我们再次访问80端口是访问不到的,因为我们映射了数据卷之后还没有编写server块中的内容

我们在/opt/docker_nginx/conf.d下新建default.conf,并插入如下内容

server {
  listen  80;
  listen  [::]:80;
  server_name  localhost;

  location / {
    root /usr/share/nginx/html;
    index  index.html  index.html;
  }
}

重启nginx: docker-compose restart



3. Nginx的正向代理和反向代理

3.1 正向代理和反向代理—知识点

正向代理:
1.正向代理服务是由客户端设立的
2.客户端了解代理服务器和目标服务器都是谁
3.帮助咱们实现突破访问权限,提高访问的速度,对目标服务器隐藏客户端的ip地址

反向代理:
1.反向代理服务器是配置在服务端的
2.客户端不知道访问的到底是哪一台服务器
3.达到负载均衡,并且可以隐藏服务器真正的ip地址

3.1 Nginx实现反向代理 — 案例

步骤:

准备一个目标服务器
启动tomcat服务器
编写nginx的配置文件(/opt/docker_nginx/conf.d/default.conf),通过Nginx访问到tomcat服务器

准备tomcat服务器

docker run -d -p 8080:8080 --name tomcat  daocloud.io/library/tomcat:8.5.15-jre8
#或者已经下载了tomcat镜像
docker run -d -p 8080:8080 --name tomcat 镜像的标识

#添加数据卷
docker run -it -v /宿主机绝对目录:/容器内目录 镜像名

default.conf文件内容如下

server {
    listen       80;
    listen  [::]:80;
    server_name  localhost;

	# 基于反向代理访问到tomcat服务器
    location / {
        proxy_pass http://{$本机IP}:8080/;
    }
}

重启nginx: docker-compose restart

这时我们访问80端口可以看到8080端口tomcat的默认首页



4. 关于Nginx的location路径映射

4.1 location路径映射—知识点

优先级关系:

(location = ) > 
	(location /xxx/yyy/zzz) > 
		(location ^~) > 
			(location ~,~*) > 
				(location /起始路径) > 
					(location /)
  1. 精准匹配:主机名后面不能带任何字符串

例如www.baidu.com不能是www.baidu.com/id=xxx

location / { }

  1. 通用匹配:匹配所有以/xxx开头的路径

例如127.0.0.1:8080/xxx xxx可以为空,为空则和=匹配一样

location /xxx { }

  1. 正则匹配:匹配所有以/xxx开头的路径

location ~ /xxx { }

  1. 匹配开头路径----异或:匹配所有以/xxx/xx开头的路径

location ^~ /xxx/xx { }

  1. 匹配结尾路径: 匹配以.gif、.jpg或者.png结尾的路径

location ~* \.(gif/jpg/png)$ { }

== root与alias的区别==


 server {
    listen       80;
    server_name  localhost;
    location / {
     #root   html;
    alias  /data/admin/;
    index  index.html index.htm;
  }
}

访问 192.12.13.1/data/admin/index.html

root的处理结果是:root路径+location路径
alias的处理结果是:使用alias路径替换location路径

alias后面必须要用“/”结束,否则会找不到文件的!!而root则可有可无~~

4.2 location路径映射 — 案例

修改/opt/docker_nginx/conf.d/default.conf 如下, 优先级 越高 越写在前面

server {
    listen       80;
    listen  [::]:80;
    server_name  localhost;

	location /index {
        proxy_pass http://{$本机IP}:8081/;	#tomcat首页
    }
	location ^~ /CR/ {
        proxy_pass http://{$本机IP}:8080/CR/;	#毕设前台首页
    }
    location / {
        proxy_pass http://{$本机IP}:8080/CRAdmin/;	#毕设后台首页
    }
}

重启nginx: docker-compose restart

访问{$本机IP}/index可以进入tomcat首页
访问{$本机IP}/CR/XXX可以进入毕设前台首页
访问{$本机IP}或者{$本机IP}:80可以进入毕设后台首页



5. Nginx负载均衡:upstream

Nginx为我们默认提供了三种负载均衡的策略:

  1. 轮询:
    将客户端发起的请求,平均分配给每一台服务器
  2. 权重:
    将客户端的请求,根据服务器的权重值不同,分配不同的数量
  3. ip_hash:
    基于发起请求的客户端的ip地址不同,他始终会将请求发送到指定的服务器上
    就是说如果这个客户端的请求的ip地址不变,那么处理请求的服务器将一直是同一个
5.1,轮询:实现Nginx轮询负载均衡机制
upstream my_serverName{
    server {$本机IP}:8080;
    server {$本机IP}:8081;
}
server {
    listen       80;
    listen  [::]:80;
    server_name  localhost;

	location / {
        proxy_pass   http://my_serverName/;	  #tomcat首页
    }
}
---------------------------------------------------
-----------------------------  总结  ----------------------
upstream 名字{
    server ip:port;
    server 域名:端口;
}
server {
    listen       80;
    listen  [::]:80;
    server_name  localhost;

	location / {
        proxy_pass http://{$upstream的名字}/;	
    }
}

1, upstream 声明应该在 server 之前;
2, upstream 的 实例名字 最好不要有下划线_

重启nginx: docker-compose restart

多次刷新{$本机IP}页面,根据版本号我们可以发现我们进入的是不同的tomcat

5.2,权重:在配置文件中upstream块中加上weight
upstream my_server{
    server {$本机IP}:8080   weight=10;
    server {$本机IP}:8081   weight=2;
}
server {
    listen       80;
    listen  [::]:80;
    server_name  localhost;

	location / {
        proxy_pass http://{$upstream的名字}/;	#tomcat首页
    }
}
5.3, ip_hash:在配置文件upstream块中加上ip_hash
upstream my_server{
	ip_hash;
    server {$本机IP}:8080;
    server {$本机IP}:8081;
}
server {
    listen       80;
    listen  [::]:80;
    server_name  localhost;

	location / {
        proxy_pass http://{$upstream的名字}/;	#tomcat首页
    }
}
5.4, 健康检查: 检查是否有服务器处于异常状态

Nginx 自带 ngx_http_upstream_module(健康检测模块)本质上服务器心跳的检查,通过定期轮询向集群里的服务器发送健康检查请求,来检查集群中是否有服务器处于异常状态;

如果某台服务器异常,客户端请求nginx反向代理进来的都不会被发送到该服务器上(直至下次轮训健康检查正常)

upstream backserver{
  server 192.168.0.1  max_fails=1 fail_timeout=40s;
  server 192.168.0.2  max_fails=1 fail_timeout=40s;
}
  1. fail_timeout : 设定服务器被认为不可用的时间段以及统计失败尝试次数的时间段,默认为10s
  2. max_fails : 设定Nginx与服务器通信的尝试失败的次数,默认为:1次


6. Nginx动静分离

6.1 Nginx动静分离 — 知识点

Nginx的并发能力公式:

worker_processes * worker_connections / 4 | 2 = Nginx最终的并发能力

动态资源需要/4,静态资源需要/2
Nginx通过动静分离来提升Nginx的并发能力,更快的给用户响应

动态资源代理

location / { proxy_pass 路径; }

静态资源代理

location  /  {
    root  静态资源路径;
    index  默认访问路径下的什么资源;
    autoindex on;  #代表展示静态资源的全部内容,以列表的形式展开
}
6.2 Nginx动静分离 — 案例

步骤:

  1. 停掉nginx: docker-compose down ;

  2. 修改 /opt/docker_nginx/docker-compose.yml 添加静态资源数据卷,映射到nginx服务器的一个目录

volumes:
- /opt/docker_nginx/conf.d/:/etc/nginx/conf.d
- /opt/docker_nginx/html/:/data/html
- /opt/docker_nginx/img/:/data/img

  1. 创建nginx: docker-compose up -d ;

  2. 在 /opt/docker_nginx/html/ 目录下创建并编辑: vi index.html ;
    在 /opt/docker_nginx/img/ 目录下ftp 放入一张图片: mv 1.jpg /opt/docker_nginx/img/ ;

  3. 修改配置文件 /opt/docker_nginx/conf.d/default.conf

# 代理到html静态资源
location /html {
   	root  /data;
    index  index.html;
}
# 代理到 img 静态资源
location /img {
   	root  /data;
    autoindex  on;   # 列表的形式展示
}
  1. 重启nginx: docker-compose restart
    访问{$本机IP}/html 查看 html静态资源,访问{$本机IP}/img 查看 img静态资源


7. Nginx集群

单点故障,避免nginx的宕机,导致整个程序的崩溃
准备多台Nginx
准备keepalived,监听nginx的健康情况
准备haproxy,提供一个虚拟的路径,统一的去接收用户的请求

在这里插入图片描述



8. Nginx之前端相关配置

参考111

8.1 适配PC与移动环境

当用户从移动端打开PC端baidu.com的场景时,将自动跳转指移动端m.baidu.com,本质上是Nginx可以通过内置变量$http_user_agent,获取到请求客户端的userAgent,从而知道当前用户当前终端是移动端还是PC,进而重定向到H5站还是PC站

server {
  location / {
    if ($http_user_agent ~* '(Android|webOS|iPhone)') {  # 移动、pc设备agent获取
      set $mobile_request '1';
    }
    if ($mobile_request = '1') {
      rewrite ^.+ http://m.baidu.com;
    }
  }
}

8.2 配置gzip

开启Nginx gzip,压缩后,静态资源的大小会大大的减少,从而可以节约大量的带宽,提高传输效率,带来更好的响应和体验

server{
  gzip on; //启动
  gzip_buffers 32 4K;
  gzip_comp_level 6; //压缩级别,1-10,数字越大压缩的越好
  gzip_min_length 100; //不压缩临界值,大于100的才压缩,一般不用改
  gzip_types application/javascript text/css text/xml;
  gzip_disable "MSIE [1-6]\."; // IE6对Gzip不友好,对Gzip
  gzip_vary on;
}

8.3 Nginx配置跨域请求

403跨域错误

当出现403跨域错误的时候,还有 No 'Access-Control-Allow-Origin' header is present on the requested resource 报错等,需要给Nginx服务器配置响应的header参数:

location / {
  add_header Access-Control-Allow-Origin *;
  add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS';
  add_header Access-Control-Allow-Headers 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization';

  if ($request_method = 'OPTIONS') {
    return 204;
  }
}

跨域代理

需求背景: 以vue-cli构建后的项目,打包后生产静态文件,其中有个index.html文件。

在开发模式下,我们可以通过devServer下的proxy来代理跨域,然后,打包后,打开index.html, devServer可不会执行。这个时候我们便可通过nginx代理跨域, 如下:

#请求跨域,这里约定代理请求url path是以/api/开头
location ^~/api/ {
  rewrite ^/api/(.*)$ /$1 break;
  proxy_pass 172.183.23.4;
}
# 这里重写了请求,将正则匹配中的第一个()中$1的path,
# 拼接到真正的请求后面,并用break停止后续匹配

如本地请求时localhost/api/getList, 经过nginx跨域代理,实际请求地址为 172.183.23.4/getList,实现跨域代理


8.4 Nginx 配置Https – SSL 认证

两个步骤:签署第三方可信任的 SSL 证书 和 配置 HTTPS

  1. 签署第三方可信任的 SSL

配置 HTTPS 要用到私钥 example.key 文件和 example.crt 证书文件,而申请证书文件的时候要用到 example.csr 文件

1)生成密钥 .key :
openssl genrsa -out nginx_quick.key 1024

2)生成证书签名请求文件 .csr :
openssl req -new -key nginx_quick.key -out nginx_quick.csr

3)生成证书签名文件 .crt ::
openssl x509 -req -days 3650 -in nginx_quick.csr -signkey nginx_quick.key -out nginx_quick.crt

  1. Nginx配置https

要开启 HTTPS 服务,在配置文件信息块(server),必须使用监听命令 listen 的 ssl 参数和定义服务器证书文件和私钥文件

server {
  #ssl参数
  listen              443 ssl;   # 监听443端口,因为443端口是https的默认端口。80为http的默认端口
  server_name         example.com;
  ssl_certificate     /etc/nginx/ssl_cert/nginx_quick.crt;    #证书文件---证书的绝对路径
  ssl_certificate_key /etc/nginx/ssl_cert/nginx_quick.key;    #私钥文件---密钥的绝对路径
}
  1. 修改 docker-compose.yml: 把自定义证书文件传到 Nginx 的对应路径下

services:
  nginx: # 服务的名称

    volumes: # 文件夹映射
      - ./nginx/nginx.conf:/etc/nginx/nginx.conf # nginx 配置文件
      - ./nginx/ssl_cert:/etc/nginx/ssl_cert # 证书文件
    ports: # 端口转发
      - "443:443"

重启后访问 https://localhost,发现页面被 Chrome 标记为不安全访问,这是因为自签证书是无效证书导致的,点击「继续前往」可正常访问到页面:


8.5 页面缓存 — 代理缓存

页面缓存主要分为三类:客户端缓存、代理缓存、服务端缓存

当 Nginx 做代理时,假如接收的大多是一些响应数据不怎么变化的请求,比如静态资源请求,使用 Nginx 缓存将大幅度提升请求速度。

Nginx 中的缓存是以文件系统上的分层数据存储的形式实现的,缓存键可配置,并且可以使用不同的特定于请求的参数来控制进入缓存的内容。

Nginx 利用 proxy_cache_pathproxy_cache 来开启内容缓存,前者用来设置缓存的路径和配置,后者用来启用缓存

http {
  proxy_cache_path /data/nginx/cache levels=1:2 keys_zone=mycache:10m max_size=10g inactive=60m;

  server {
    proxy_cache mycache;
  }
}

上边设置了一个缓存 mycache,并在 server 中启用:

1)/data/nginx/cache 指定了本地缓存的根目录;

2)level 代表缓存目录结构是两层的,最多设置3层,数字代表命名长度,比如 1:2 就会生成诸如 /data/nginx/cache/w/0d 的目录,对于大量缓存场景,合理的分层缓存是必要的;

3)keys_zone 设置了一个共享内存区,10m 代表内存区的大小,该内存区用于存储缓存键和元数据,保证 Nginx 在不检索磁盘的情况下能够快速判断出缓存是否命中;

4)max_size 设置了缓存的上限,默认是不限制;

5)inactive 设置了缓存在未被访问时能够持续保留的最长时间,也就是失活时间。


8.6 Nginx 替换前端页面的样式
location / {
    root /usr/share/nginx/html;
    index index.html index.htm;
    try_files $uri $uri/ /index.html;
    proxy_ssl_verify off;
    # 第一个参数是要被替换的,第二个参数是替换后的
    sub_filter '</head>' '</head> <style>.el-container > .el-aside, .el-container > .el-header{display: none;}</style>';
    sub_filter_once off; #替换所有的,默认是on,替换第一个
}

9. Nginx简单总结

nginx 替换 样式(头部、左侧导航菜单)

location / {
        root /usr/share/nginx/html;
        index index.html index.htm;
        try_files $uri $uri/ /index.html;
        proxy_ssl_verify off;
        # 第一个参数是要被替换的,第二个参数是替换后的
        sub_filter '</head>' '</head> <style>.el-container > .el-aside, .el-container > .el-header{display: none;}</style>';
        sub_filter_once off; #替换所有的,默认是on,替换第一个
    }

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

负载均衡

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值