导航菜单

  • 0.api
  • 0.Async
  • 0.module
  • 1.ES2015
  • 2.Promise
  • 3.Node
  • 4.NodeInstall
  • 5.REPL
  • 6.NodeCore
  • 7.module&NPM
  • 8.Encoding
  • 9.Buffer
  • 10.fs
  • 11.Stream-1
  • 11.Stream-2
  • 11.Stream-3
  • 11.Stream-4
  • 12-Network-2
  • 12.NetWork-3
  • 12.Network-1
  • 13.tcp
  • 14.http-1
  • 14.http-2
  • 15.compress
  • 16.crypto
  • 17.process
  • 18.yargs
  • 19.cache
  • 20.action
  • 21.https
  • 22.cookie
  • 23.session
  • 24.express-1
  • 24.express-2
  • 24.express-3
  • 24.express-4
  • 25.koa-1
  • 26.webpack-1-basic
  • 26.webpack-2-optimize
  • 26.webpack-3-file
  • 26.webpack-4.tapable
  • 26.webpack-5-AST
  • 26.webpack-6-sources
  • 26.webpack-7-loader
  • 26.webpack-8-plugin
  • 26.webpack-9-hand
  • 26.webpack-10-prepare
  • 28.redux
  • 28.redux-jwt-back
  • 28.redux-jwt-front
  • 29.mongodb-1
  • 29.mongodb-2
  • 29.mongodb-3
  • 29.mongodb-4
  • 29.mongodb-5
  • 29.mongodb-6
  • 30.cms-1-mysql
  • 30.cms-2-mysql
  • 30.cms-3-mysql
  • 30.cms-4-nunjucks
  • 30.cms-5-mock
  • 30.cms-6-egg
  • 30.cms-7-api
  • 30.cms-8-roadhog
  • 30.cms-9-yaml
  • 30.cms-10-umi
  • 30.cms-12-dva
  • 30.cms-13-dva-ant
  • 30.cms-14-front
  • 30.cms-15-deploy
  • 31.dva
  • 31.cms-13-dva-antdesign
  • 33.redis
  • 34.unittest
  • 35.jwt
  • 36.websocket-1
  • 36.websocket-2
  • 38.chat-api-1
  • 38.chat-api-2
  • 38.chat-3
  • 38.chat-api-3
  • 38.chat
  • 38.chat2
  • 38.chat2
  • 39.crawl-0
  • 39.crawl-1
  • 39.crawl-2
  • 40.deploy
  • 41.safe
  • 42.test
  • 43.nginx
  • 44.enzyme
  • 45.docker
  • 46.elastic
  • 47.oauth
  • 48.wxpay
  • index
  • 52.UML
  • 53.design
  • index
  • 54.linux
  • 57.ts
  • 56.react-ssr
  • 58.ts_react
  • 59.ketang
  • 59.ketang2
  • 61.1.devops-linux
  • 61.2.devops-vi
  • 61.3.devops-user
  • 61.4.devops-auth
  • 61.5.devops-shell
  • 61.6.devops-install
  • 61.7.devops-system
  • 61.8.devops-service
  • 61.9.devops-network
  • 61.10.devops-nginx
  • 61.11.devops-docker
  • 61.12.devops-jekins
  • 61.13.devops-groovy
  • 61.14.devops-php
  • 61.15.devops-java
  • 61.16.devops-node
  • 61.17.devops-k8s
  • 62.1.react-basic
  • 62.2.react-state
  • 62.3.react-high
  • 62.4.react-optimize
  • 62.5.react-hooks
  • 62.6.react-immutable
  • 62.7.react-mobx
  • 62.8.react-source
  • 63.1.redux
  • 63.2.redux-middleware
  • 63.3.redux-hooks
  • 63.4.redux-saga
  • 63.5.redux-saga-hand
  • 64.1.router
  • 64.2.router-connected
  • 65.1.typescript
  • 65.2.typescript
  • 65.3.typescript
  • 65.4.antd
  • 65.4.definition
  • 66-1.vue-base
  • 66-2.vue-component
  • 66-3.vue-cli3.0
  • 66-4.$message组件
  • 66-5.Form组件
  • 66-6.tree
  • 66-7.vue-router-apply
  • 66-8.axios-apply
  • 66-9.vuex-apply
  • 66-10.jwt-vue
  • 66-11.vue-ssr
  • 66-12.nuxt-apply
  • 66-13.pwa
  • 66-14.vue单元测试
  • 66-15.权限校验
  • 67-1-network
  • 68-2-wireshark
  • 7.npm2
  • 69-hooks
  • 70-deploy
  • 71-hmr
  • 72.deploy
  • 73.import
  • 74.mobile
  • 75.webpack-1.文件分析
  • 75.webpack-2.loader
  • 75.webpack-3.源码流程
  • 75.webpack-4.tapable
  • 75.webpack-5.prepare
  • 75.webpack-6.resolve
  • 75.webpack-7.loader
  • 75.webpack-8.module
  • 75.webpack-9.chunk
  • 75.webpack-10.asset
  • 75.webpack-11.实现
  • 76.react_optimize
  • 77.ts_ketang_back
  • 77.ts_ketang_front
  • 78.vue-domdiff
  • 79.grammar
  • 80.tree
  • 81.axios
  • 82.1.react
  • 82.2.react-high
  • 82.3.react-router
  • 82.4.redux
  • 82.5.redux_middleware
  • 82.6.connected
  • 82.7.saga
  • 82.8.dva
  • 82.8.dva-source
  • 82.9.roadhog
  • 82.10.umi
  • 82.11.antdesign
  • 82.12.ketang-front
  • 82.12.ketang-back
  • 83.upload
  • 84.graphql
  • 85.antpro
  • 86.1.uml
  • 86.2.design
  • 87.postcss
  • 88.react16-1
  • 89.nextjs
  • 90.react-test
  • 91.react-ts
  • 92.rbac
  • 93.tsnode
  • 94.1.JavaScript
  • 94.2.JavaScript
  • 94.3.MODULE
  • 94.4.EventLoop
  • 94.5.文件上传
  • 94.6.https
  • 94.7. nginx
  • 95.1. react
  • 95.2.react
  • 96.1.react16
  • 96.2.fiber
  • 96.3.fiber
  • 97.serverless
  • 98.websocket
  • 100.1.react-basic
  • 101.1.monitor
  • 101.2.monitor
  • 102.java
  • 103.1.webpack-usage
  • 103.2.webpack-bundle
  • 103.3.webpack-ast
  • 103.4.webpack-flow
  • 103.5.webpack-loader
  • 103.6.webpack-tapable
  • 103.7.webpack-plugin
  • 103.8.webpack-optimize1
  • 103.9.webpack-optimize2
  • 103.10.webpack-hand
  • 103.11.webpack-hmr
  • 103.11.webpack5
  • 103.13.splitChunks
  • 103.14.webpack-sourcemap
  • 103.15.webpack-compiler1
  • 103.15.webpack-compiler2
  • 103.16.rollup.1
  • 103.16.rollup.2
  • 103.16.rollup.3
  • 103.16.vite.basic
  • 103.16.vite.source
  • 103.16.vite.plugin
  • 103.16.vite.1
  • 103.16.vite.2
  • 103.17.polyfill
  • 104.1.binary
  • 104.2.binary
  • 105.skeleton
  • 106.1.react
  • 106.2.react_hooks
  • 106.3.react_router
  • 106.4.redux
  • 106.5.redux_middleware
  • 106.6.connected-react-router
  • 106.6.redux-first-history
  • 106.7.redux-saga
  • 106.8.dva
  • 106.9.umi
  • 106.10.ketang
  • 106.11.antdesign
  • 106.12.antpro
  • 106.13.router-6
  • 106.14.ssr
  • 106.15.nextjs
  • 106.16.1.cms
  • 106.16.2.cms
  • 106.16.3.cms
  • 106.16.4.cms
  • 106.16.mobx
  • 106.17.fomily
  • 107.fiber
  • 108.http
  • 109.1.webpack_usage
  • 109.2.webpack_source
  • 109.3.dll
  • 110.nest.js
  • 111.xstate
  • 112.Form
  • 113.redux-saga
  • 114.react+typescript
  • 115.immer
  • 116.pro5
  • 117.css-loader
  • 118.1.umi-core
  • 119.2.module-federation
  • 119.1.module-federation
  • 120.create-react-app
  • 121.react-scripts
  • 122.react-optimize
  • 123.jsx-runtime
  • 124.next.js
  • 125.1.linux
  • 125.2.linux-vi
  • 125.3.linux-user
  • 125.4.linux-auth
  • 125.5.linux-shell
  • 125.6.linux-install
  • 125.7.linux-system
  • 125.8.linux-service
  • 125.9.linux-network
  • 125.10.nginx
  • 125.11.docker
  • 125.12.ci
  • 125.13.k8s
  • 125.14.k8s
  • 125.15.k8s
  • 125.16.k8s
  • 126.11.react-1
  • 126.12.react-2
  • 126.12.react-3
  • 126.12.react-4
  • 126.12.react-5
  • 126.12.react-6
  • 126.12.react-7
  • 126.12.react-8
  • 127.frontend
  • 128.rollup
  • 129.px2rem-loader
  • 130.health
  • 131.hooks
  • 132.keepalive
  • 133.vue-cli
  • 134.react18
  • 134.2.react18
  • 134.3.react18
  • 135.function
  • 136.toolkit
  • 137.lerna
  • 138.create-vite
  • 139.cli
  • 140.antd
  • 141.react-dnd
  • 142.1.link
  • 143.1.gulp
  • 143.2.stream
  • 143.3.gulp
  • 144.1.closure
  • 144.2.v8
  • 144.3.gc
  • 145.react-router-v6
  • 146.browser
  • 147.lighthouse
  • 148.1.basic
  • 148.2.basic
  • 148.3.basic
  • 148.4.basic
  • 148.5.basic
  • 149.1.vite
  • 149.2.vite
  • 149.3.vite
  • 149.4.vite
  • 150.react-window
  • 151.react-query
  • 152.useRequest
  • 153.transition
  • 154.emotion
  • 155.1.formily
  • 155.2.formily
  • 155.3.formily
  • 155.3.1.mobx.usage
  • 155.3.2.mobx.source
  • 156.vue-loader
  • 103.11.mf
  • 157.1.react18
  • 158.umi4
  • 159.rxjs
  • 159.rxjs2
  • 160.bff
  • 161.zustand
  • 162.vscode
  • 163.emp
  • 164.cors
  • 1. nginx
  • 2. 学习环境
    • 2.1 操作系统
    • 2.2 环境确认
      • 2.2.1 关闭 iptables
      • 2.2.2 确认停用 selinux
      • 2.2.3 安装依赖模块
  • 3. nginx的优势
  • 4. nginx安装
    • 4.1 版本分类
    • 4.2 下载地址
    • 4.3 CentOS下YUM安装
  • 5. 目录
    • 5.1 安装目录
    • 5.2 配置文件
  • 5.3 编译参数
    • 5.3.1 安装目录和路径
    • 5.3.2 执行对应模块时,nginx所保留的临时性文件
    • 5.3.3 设置nginx进程启动的用户和用户组
    • 5.3.4 设置额外的参数将被添加到CFLAGS变量
    • 5.3.5 设置附加的参数,链接系统库
    • 5.3.6 其它参数
  • 5. 配置文件
    • 5.1 全局和服务配置
    • 5.2 全局和服务配置
  • 6. 启动和重新加载
  • 7. 日志类型
    • 7.1 日志类型
    • 7.2 log_format
    • 7.3 HTTP请求变量
    • 7.4 内置变量
  • 8. nginx实战
    • 8.1 静态资源Web服务
    • 8.2 CDN
      • 8.2.1 配置语法
        • 8.2.1.1 sendfile
        • 8.2.1.2 tcp_nopush
        • 8.2.1.2 tcp_nodelay
        • 8.2.1.3 gzip
        • 8.2.1.4 gzip_comp_level
        • 8.2.1.5 gzip_http_version
        • 8.2.1.6 http_gzip-static_module
    • 8.3 浏览器缓存
      • 8.3.1 expires
    • 8.4 跨域
    • 8.5 防盗链
    • 8.6 代理服务
      • 8.6.1 配置
      • 8.6.2 反向代理
      • 8.6.3 正向代理
    • 8.7 负载均衡
      • 8.7.1 upstream
      • 8.7.2 后端服务器调试状态
      • 8.7.3 分配方式
    • 8.8 缓存

1. nginx #

nginx是一个开源且高性能、可靠的HTTP中间件和代理服务器

2. 学习环境 #

2.1 操作系统 #

CENTOS>=7.0,位数 X64 CENTOS 7.2

2.2 环境确认 #

2.2.1 关闭 iptables #

iptables命令是Linux上常用的防火墙软件

功能 命令
停止防火墙 systemctl stop firewalld.service
永久关闭防火墙 systemctl disable firewalld.service

2.2.2 确认停用 selinux #

  • 安全增强型 Linux(Security-Enhanced Linux)简称 SELinux,它是一个 Linux 内核模块,也是 Linux 的一个安全子系统。
  • SELinux 主要作用就是最大限度地减小系统中服务进程可访问的资源(最小权限原则)。
功能 命令
检查状态 getenforce
检查状态 /usr/sbin/sestatus -v
临时关闭 setenforce 0
永久关闭 /etc/selinux/config SELINUX=enforcing改为SELINUX=disabled

2.2.3 安装依赖模块 #

yum  -y install gcc gcc-c++ autoconf pcre pcre-devel make automake
yum  -y install wget httpd-tools vim

3. nginx的优势 #

  • IO多路复用 多个描述符的IO操作都能在一个线程里并发交替顺序完成,复用线程
    • select 线性遍历文件描述符列表 1. 效率低下 2.最多只能有1024
    • epoll 每当fd就绪,采用系统回调函数将fd放入 1.效率高 2.没有1024限制
  • CPU亲和 一种把CPU核心和Nginx工作进程绑定方式,把每个worker进程固定在一个CPU上执行,减少切换CPU和提交缓存命中率,获得更好的性能。
  • sendfile 零拷贝传输模式 ![usercore]

usercore

4. nginx安装 #

4.1 版本分类 #

  • Mainline version 开发版
  • Stable version 稳定版
  • Legacy versions 历史版本

4.2 下载地址 #

  • nginx
  • linux_packages

4.3 CentOS下YUM安装 #

/etc/yum.repos.d/nginx.repo

[nginx]
name=nginx repo
baseurl=http://nginx.org/packages/centos/7/$basearch/
gpgcheck=0
enabled=1
yum install nginx -y
nginx -v
nginx -V

5. 目录 #

5.1 安装目录 #

查看配置文件和目录

rpm -ql nginx

5.2 配置文件 #

类型 路径 用途
配置文件 /etc/logrotate.d/nginx 用于logrotate服务的日志切割
配置文件 /etc/nginx /etc/nginx/nginx.conf /etc/nginx/conf.d /etc/nginx/conf.d/default.conf 主配置文件
配置文件 /etc/nginx/fastcgi_params /etc/nginx/scgi_params /etc/nginx/uwsgi_params cgi配置,fastcgi配置
配置文件 /etc/nginx/koi-utf /etc/nginx/koi-win /etc/nginx/win-utf 编码转换映射转化文件
配置文件 /etc/nginx/mime.types 设置http协议的Content-Type与扩展名对应关系
配置文件 /usr/lib/systemd/system/nginx-debug.service /usr/lib/systemd/system/nginx.service /etc/sysconfig/nginx /etc/sysconfig/nginx-debug 用于配置系统守护进程管理器管理方式
配置文件 /etc/nginx/modules /usr/lib64/nginx/modules nginx模块目录
命令 /usr/share/doc/nginx-1.14.0 /usr/share/doc/nginx-1.14.0/COPYRIGHT nginx的手册和帮助文件
目录 /var/cache/nginx nginx的缓存目录
目录 /var/log/nginx nginx的日志目录

5.3 编译参数 #

5.3.1 安装目录和路径 #

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

5.3.2 执行对应模块时,nginx所保留的临时性文件 #

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

5.3.3 设置nginx进程启动的用户和用户组 #

--user=nginx 
--group=nginx 

5.3.4 设置额外的参数将被添加到CFLAGS变量 #

--with-cc-opt='-O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector-strong 

5.3.5 设置附加的参数,链接系统库 #

--with-ld-opt='-Wl,-z,relro -Wl,-z,now -pie'

5.3.6 其它参数 #

--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 
--param=ssp-buffer-size=4 -grecord-gcc-switches -m64 -mtune=generic -fPIC' 

5. 配置文件 #

  • /etc/nginx/nginx.conf
  • /etc/nginx/conf.d/*.conf /etc/nginx/conf.d/default.conf

5.1 全局和服务配置 #

分类 配置项 作用
全局 user 设置nginx服务的系统使用用户
全局 worker_processes 工作进程数,一般和CPU数量相同
全局 error_log nginx的错误日志
全局 pid nginx服务启动时的pid

5.2 全局和服务配置 #

分类 配置项 作用
events worker_connections 每个进程允许的最大连接数 10000
events use 指定使用哪种模型(select/poll/epoll),建议让nginx自动选择,linux内核2.6以上一般能使用epoll,提高性能。

/etc/nginx/nginx.conf

user  nginx;   设置nginx服务的系统使用用户  
worker_processes  1;  工作进程数,一般和CPU数量相同 

error_log  /var/log/nginx/error.log warn;   nginx的错误日志  
pid        /var/run/nginx.pid;   nginx服务启动时的pid

events {
    worker_connections  1024;每个进程允许的最大连接数 10000
}

http {
    include       /etc/nginx/mime.types;//文件后缀和类型类型的对应关系
    default_type  application/octet-stream;//默认content-type

    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;//默认访问日志

    sendfile        on;//启用sendfile
    #tcp_nopush     on;//懒发送

    keepalive_timeout  65;//超时时间是65秒

    #gzip  on;gzip压缩

    include /etc/nginx/conf.d/*.conf;//包含的子配置文件
}

default.conf

server {
    listen       80;  //监听的端口号
    server_name  localhost;  //用域名方式访问的地址

    #charset koi8-r; //编码
    #access_log  /var/log/nginx/host.access.log  main;  //访问日志文件和名称

    location / {
        root   /usr/share/nginx/html;  //静态文件根目录
        index  index.html index.htm;  //首页的索引文件
    }

    #error_page  404              /404.html;  //指定错误页面

    # redirect server error pages to the static page /50x.html
    # 把后台错误重定向到静态的50x.html页面
    error_page   500 502 503 504  /50x.html; 
    location = /50x.html {
        root   /usr/share/nginx/html;
    }

    # proxy the PHP scripts to Apache listening on 127.0.0.1:80
    # 代理PHP脚本到80端口上的apache服务器
    #location ~ \.php$ {
    #    proxy_pass   http://127.0.0.1;
    #}

    # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
    # 把PHP脚本9000端口上监听的FastCGI服务
    #location ~ \.php$ {
    #    root           html;
    #    fastcgi_pass   127.0.0.1:9000;
    #    fastcgi_index  index.php;
    #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
    #    include        fastcgi_params;
    #}

    # deny access to .htaccess files, if Apache's document root
    # concurs with nginx's one
    # 不允许访问.htaccess文件
    #location ~ /\.ht {
    #    deny  all;
    #}
}

6. 启动和重新加载 #

systemctl restart nginx.service
systemctl reload nginx.service
nginx -s reload

7. 日志类型 #

7.1 日志类型 #

  • access_.log 访问日志
  • error.log 错误日志

7.2 log_format #

类型 用法
语法 log_format name [escape=default[json] string]
默认 log_format combined ...
Context http

案例

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

 log_format  zfpx  '$arg_name $http_referer sent_http_date"';
 access_log  /var/log/nginx/access.log  main;    

 221.216.143.110 - - [09/Jun/2018:22:41:18 +0800] "GET / HTTP/1.1" 200 612 "-" "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36" "-"

7.3 HTTP请求变量 #

名称 含义 例子
arg_PARAMETER 请求参数 $arg_name
http_HEADER 请求头 $http_referer
sent_http_HEADER 响应头 sent_http_cookie

7.4 内置变量 #

ngx_http_log_module log_format

名称 含义
$remote_addr 客户端地址
$remote_user 客户端用户名称
$time_local 访问时间和时区
$request 请求的URI和HTTP协议
$http_host 请求地址,即浏览器中你输入的地址(IP或域名)
$status HTTP请求状态
$body_bytes_sent 发送给客户端文件内容大小

8. nginx实战 #

8.1 静态资源Web服务 #

  • 静态资源:一般客户端发送请求到web服务器,web服务器从内存在取到相应的文件,返回给客户端,客户端解析并渲染显示出来。
  • 动态资源:一般客户端请求的动态资源,先将请求交于web容器,web容器连接数据库,数据库处理数据之后,将内容交给web服务器,web服务器返回给客户端解析渲染处理。
类型 种类
浏览器渲染 HTML、CSS、JS
图片 JPEG、GIF、PNG
视频 FLV、MPEG
下载文件 Word、Excel

8.2 CDN #

  • CDN的全称是Content Delivery Network,即内容分发网络。
  • CDN系统能够实时地根据网络流量和各节点的连接、负载状况以及到用户的距离和响应时间等综合信息将用户的请求重新导向离用户最近的服务节点上。其目的是使用户可就近取得所需内容,解决 Internet网络拥挤的状况,提高用户访问网站的响应速度。

cdn

8.2.1 配置语法 #

8.2.1.1 sendfile #

不经过用户内核发送文件

类型 种类
语法 sendfile on / off
默认 sendfile off;
上下文 http,server,location,if in location
8.2.1.2 tcp_nopush #

在sendfile开启的情况 下,提高网络包的传输效率

类型 种类
语法 tcp_nopush on / off
默认 tcp_nopush off;
上下文 http,server,location
8.2.1.2 tcp_nodelay #

在keepalive连接下,提高网络包的传输实时性

类型 种类
语法 tcp_nodelay on / off
默认 tcp_nodelay on;
上下文 http,server,location
8.2.1.3 gzip #

压缩文件可以节约带宽和提高网络传输效率

类型 种类
语法 gzip on / off
默认 gzip off;
上下文 http,server,location
8.2.1.4 gzip_comp_level #

压缩比率越高,文件被压缩的体积越小

类型 种类
语法 gzip_comp_level level
默认 gzip_comp_level 1;
上下文 http,server,location
8.2.1.5 gzip_http_version #

压缩HTTP版本

类型 种类
语法 gzip_http_version 1.0/1.1
默认 gzip_http_version 1.1;
上下文 http,server,location
8.2.1.6 http_gzip-static_module #

先找磁盘上找同名的.gz这个文件是否存在,节约CPU的压缩时间和性能损耗

类型 种类
语法 gzip_static on/off
默认 gzip_static off;
上下文 http,server,location
location ~ .*\.(jpg|png|gif)$ {
        gzip off;
        gzip_http_version 1.1;
       gzip_comp_level 3;
       gzip_types image/jpeg image/png image/gif;
        root /data/images;
    }

    location ~ .*\.(html|js|css)$ {
        gzip on;
        gzip_min_length 1k;
        gzip_http_version 1.1;
        gzip_comp_level 9;
        gzip_types  text/css application/javascript;
        root /data/html;
    }

    location ~ ^/download {
        gzip_static on;
        tcp_nopush on; 
        root /data/download;
    }

8.3 浏览器缓存 #

校验本地缓存是否过期

类型 种类
检验是否过期 Expires、Cache-Control(max-age)
Etag Etag
Last-Modified Last-Modified

8.3.1 expires #

添加Cache-Control、Expires头

类型 种类
语法 expires time
默认 expires off;
上下文 http,server,location
location ~ .*\.(jpg|png|gif)$ {
        expires 24h;
}

8.4 跨域 #

类型 种类
语法 add_header name value
默认 add_header --;
上下文 http,server,location
location ~ .*\.json$ {
        add_header Access-Control-Allow-Origin http://localhost:3000;
        add_header Access-Control-Allow-Methods GET,POST,PUT,DELETE,OPTIONS;
        root /data/json;
    }
let xhr = new XMLHttpRequest();
        xhr.open('GET', 'http://47.104.184.134/users.json', true);
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4 && xhr.status == 200) {
                console.log(xhr.responseText);
            }
        }
xhr.send();

8.5 防盗链 #

  • 防止网站资源被盗用
  • 保证信息安全
  • 防止流量过量
  • 区别哪些请求是非正常的用户请求
  • 使用http_refer防盗链
类型 种类
语法 valid_referers none block server_names string...
默认 -
上下文 server,location
location ~ .*\.(jpg|png|gif)$ {
        expires 1h;
        gzip off;
        gzip_http_version 1.1;
        gzip_comp_level 3;
        gzip_types image/jpeg image/png image/gif;
+        valid_referers none blocked 47.104.184.134;
+        if ($invalid_referer) {
+           return 403;
+        }
        root /data/images;
    }

8.6 代理服务 #

8.6.1 配置 #

类型 种类
语法 proxy_pass URL
默认 -
上下文 server,location

8.6.2 反向代理 #

反向代理的对象的服务端 fanproxy

resolver 8.8.8.8;
location ~ ^/api {
      proxy_pass http://127.0.0.1:3000;
}

8.6.3 正向代理 #

正向代理的对象是客户端 positiveproxy

location / {
        proxy_pass http://$http_host$request_uri;
    }

8.7 负载均衡 #

nginxbalance

  • 使用集群是网站解决高并发、海量数据问题的常用手段。
  • 当一台服务器的处理能力、存储空间不足时,不要企图去换更强大的服务器,对大型网站而言,不管多么强大的服务器,都满足不了网站持续增长的业务需求。
  • 这种情况下,更恰当的做法是增加一台服务器分担原有服务器的访问及存储压力。通过负载均衡调度服务器,将来自浏览器的访问请求分发到应用服务器集群中的任何一台服务器上,如果有更多的用户,就在集群中加入更多的应用服务器,使应用服务器的负载压力不再成为整个网站的瓶颈。

8.7.1 upstream #

类型 种类
语法 upstream name {}
默认 -
上下文 http
upstream zfpx {
  ip_hash;
  server localhost:3000;
  server localhost:4000;
  server localhost:5000;
}

server {
    location / {
        proxy_pass http://zfpx;
    }

8.7.2 后端服务器调试状态 #

状态 描述
down 不参与负载均衡
backup 备份的服务器
max_fails 允许请求失败的次数
fail_timeout 经过max_fails失败后,服务暂停的时间
max_conns 限制最大的接收的连接数
upstream zfpx {
  server localhost:3000 down;
  server localhost:4000 backup;
  server localhost:5000 max_fails=1 fail_timeout=10s;
}

8.7.3 分配方式 #

类型 种类
轮询(默认) 每个请求按时间顺序逐一分配到不同的后端服务器,如果后端服务器down掉,能自动剔除。
weight(加权轮询) 指定轮询几率,weight和访问比率成正比,用于后端服务器性能不均的情况。
ip_hash 每个请求按访问ip的hash结果分配,这样每个访客固定访问一个后端服务器,可以解决session的问题。
url_hash(第三方) 按访问的URL地址来分配 请求,每个URL都定向到同一个后端 服务器上(缓存)
fair(第三方) 按后端服务器的响应时间来分配请求,响应时间短的优先分配。
least_conn 最小连接数,哪个连接少就分给谁
自定义hash hash自定义key

8.8 缓存 #

nginx代理缓存

proxy_cache

http{  
    proxy_cache_path /data/nginx/tmp-test levels=1:2 keys_zone=tmp-test:100m inactive=7d max_size=1000g;  
}  
  • proxy_cache_path 缓存文件路径
  • levels 设置缓存文件目录层次;levels=1:2 表示两级目录
  • keys_zone 设置缓存名字和共享内存大小
  • inactive 在指定时间内没人访问则被删除
  • max_size 最大缓存空间,如果缓存空间满,默认覆盖掉缓存时间最长的资源。
location /tmp-test/ {  
  proxy_cache tmp-test;  
  proxy_cache_valid  200 206 304 301 302 10d;  
  proxy_cache_key $uri;  
  proxy_set_header Host $host:$server_port;  
  proxy_set_header X-Real-IP $remote_addr;  
  proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;  
  proxy_pass http://127.0.0.1:8081/media_store.php/tmp-test/;  
}
  • proxy_cache tmp-test 使用名为tmp-test的对应缓存配置
  • proxy_cache_valid 200 206 304 301 302 10d; 对httpcode为200…的缓存10天
  • proxy_cache_key $uri 定义缓存唯一key,通过唯一key来进行hash存取
  • proxy_set_header 自定义http header头,用于发送给后端真实服务器。
  • proxy_pass 指代理后转发的路径,注意是否需要最后的/

访问验证

请输入访问令牌

Token不正确,请重新输入