当前位置:首页 > 服务端 > 怎么安装nginx

怎么安装nginx

Nginx快速安装

  • Nginx快速搭建与基本使用
    • Mainline version - 开发版
    • Stable version - 稳定版
    • Legacy version - 历史版本

新建nginx的yum源

# 进入到/etc/yum.repos.d目录
cd /etc/yum.repos.d
# 新建文件 nginx.repo 文件
vim ./nginx.repo

[nginx]
name=nginx repo
baseurl=http://nginx.org/packages/mainline/centos/7/$basearch/
gpgcheck=0
enabled=1

# 保存 测试
yum list | grep nginx
# 展示出有关nginx的相关列表即为yum源安装成功

# 安装nginx
yum install nginx

# 测试nginx是否安装成功
nginx -v # 看到安装的版本
nginx -V # 看到安装编译的参数

Nginx一些常用命令

# 重新启动Nginx
systemctl restart nginx.service
systemctl reload nginx.service
# 检查配置文件是否正确
nginx -t -c /etc/nginx/nginx.conf
# 重新加载配置
nginx -s reload -c /etc/nginx/nginx.conf
# 查看nginx启用的端口
netstat -lintp | grep nginx
# 停止nginx
ps -ef|grep nginx # 找到nginx: master process ./nginx 对应的进程号
kill -QUIT 2072

什么是Nginx

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

常见的HTTP服务

  • HTTPD-Apache基金会
  • IIS-微软
  • GWS-Google

Nginx的特性

为什么选择Nginx

  1. IO多路复用epoll

    • 多个描述符的I/O操作都能再一个线程内并发交替的顺序完成任务,这就叫I/O多路复用,这里的“复用”指的是复用同一个线程。
    • 什么是epoll
      • IO多路复用的实现方式select、poll、epoll
  2. 轻量级

    • 功能模块少

    • 代码模块化

Nginx的目录和配置语法

安装目录:

# 此命令会列出yum安装的相关rpm包和相关的配置文件 
rpm -ql nginx

目录及作用列表

路径 类型 作用
配置文件 Nginx日志轮转,用于logrotate服务的日志切割
/etc/nginx 目录、配置文件 Nginx主配置文件
/etc/nginx/nginx.conf 目录、配置文件 Nginx主配置文件
/etc/nginx/conf.d 目录、配置文件 Nginx主配置文件
/etc/nginx/conf.d/default.confg 目录、配置文件 Nginx主配置文件
/etc/nginx/fastcgi_params 配置文件 cgi配置相关,fastcgi配置
/etc/nginx/uwsgi_params 配置文件 cgi配置相关,fastcgi配置
/etc/nginx/scgi_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 配置文件 用于配置出系统守护进程管理器管理方式
/usr/lib64/nginx/modules 目录 Nginx模块目录
/etc/nginx/modules 目录 Nginx模块目录
/usr/sbin/nginx 命令 Nginx服务的启动管理的终端命令
/usr/sbin/nginx-debug 命令 Nginx服务的启动管理的终端命令
/usr/share/doc/nginx-1.12.0 文件、目录 Nginx的手册和帮助文件
/usr/share/doc/nginx-1.12.0/COPYRIGHT 文件、目录 Nginx的手册和帮助文件
/usr/share/man/man8/nginx.8.gz 文件、目录 Nginx的手册和帮助文件
/var/cache/nginx 目录 Nginx的缓存目录
/var/log/nginx 目录 Nginx的日志目录

编译参数:

安装编译参数:

# 可以查看Nginx在安装的时候用到了什么参数和安装了什么模块(--with-xxx)
nginx -V

Nginx基本配置语法:

nginx.conf主配置文件:

# 设置nginx服务的系统使用用户
user  nginx;
# 工作进程数:一般和CPU的核心数保持一致
worker_processes  1;
# nginx的错误日志
error_log  /var/log/nginx/error.log warn;
# nginx服务启动时候pid存放位置
pid        /var/run/nginx.pid;


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


http {
	server {
        listen	80; # 监听的80端口
        server_name	localhost; # 有虚拟主机域名的可以换成主机域名
        location / { # 跟随上一个 server_name
            root	/usr/share/nginx/html;
            index	index.html	index.htm;
        }
        
        error_page	500 502 503 504 /50x.html;
        location = /50x.html { # 跟随上一个 error_page
            root	/usr/share/nginx/html;
        }
	}
	# 一个http对应多个server 一个server可以有多个location
	server {
        ...
	}
    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; # main对应的上方的log_format的格式名字

    # 开启零拷贝, 直接从磁盘到网卡
    sendfile        on;
    #tcp_nopush     on;

    keepalive_timeout  65; # 客户端与服务端超时的时间65s

    #gzip  on;

	# 包含了该目录下所有以.conf结尾的配置文件
    include /etc/nginx/conf.d/*.conf;
}
关键字 作用
user 设置nginx服务的系统使用用户
worker_processes 工作进程数
error_log nginx的错误日志
pid nginx服务启动时候pid

events模块

  • worker_connections:每个进程允许最大连接数
  • use:工作进程数,定义使用哪种内核模型
# 进入到配置文件目录
cd /etc/nginx/conf.d/
# 打开默认配置文件 default.conf


server {
    listen       80;
    server_name  localhost; # 不同的server可以根据server_name进行区别

    #charset koi8-r;
    #access_log  /var/log/nginx/log/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
    #
    error_page   500 502 503 504 404  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }

    # proxy the PHP scripts to Apache listening on 127.0.0.1:80
    #
    #location ~ \.php$ {
    #    proxy_pass   http://127.0.0.1;
    #}

    # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
    #
    #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
    #
    #location ~ /\.ht {
    #    deny  all;
    #}
}

HTTP请求

  • request - 包括请求行、请求头部、请求数据
  • response - 包括状态行、消息包头、相应正文

Nginx日志log_format

Nginx日志类型:

  • error.log
  • access_log

log_format:

Syntax: log_format name [escape=default|json] string …;(语法)

Default: log_format combined “…”;

Context: http(只能配置在http模块下面)

Nginx变量:

  • HTTP请求变量 - arg_PARAMETER、http_HEADER(request头部信息)、sent_http_HEADER(response头部信息)

    例如:如果要记录http的头部信息中的User-Agent信息 就写为 $http_user_agent

  • 内置变量 - Nginx内置的

    参考官网的详细介绍

    • $remote_addr:表示客户端地址
    • $remote_user:客户端请求服务端认证的用户名(默认没开启认证模块不会起作用)
    • $time_local:表示nginx的时间
    • $request:request头的请求行
    • $status:返回的状态
    • $body_bytes_sent:服务端给客户端响应body的大小
    • $http_referer:记录请求的来源,多用于防盗链
    • $http_user_agent:客户端浏览器的信息
    • $http_x_forwarded_for:记录每一级携带的信息
  • 自定义变量 - 自己定义(详情见nginx+lua)

Nginx模块介绍

Nginx的官方模块:

# 查看nginx编译的相关模块(--with-xxx)
nginx -V

第三方模块:(详细在nginx+lua)

stub_status模块

作用:访问相应路径会展示出Nginx的状态

配置语法:

Syntax: stub_status;

Default: -

Context: server, location

server {
	...
    location /mystatus {
        stub_status;
    }
    ...
}

# 返回给浏览器
Active connections: 2 # nginx活跃的连接数
server accepts handled requests
396	396	1293 # (1)nginx处理的握手的总的连接次数(2)nginx的连接数(3)总的请求数 1=2表示没有丢失
Reading: 0 Writing: 1 Waiting: 1 

random_index模块

作用:目录中选择一个随机主页

配置语法:

Syntax: random_index on | off;

Default: random_index off;

Context: location

server {
    ...
    location / {
        root	/usr/share/nginx/html;
        random_index	on;
        #index	index.html index.htm;
    }
}

sub_module模块

语法配置一:(作用:Http内容替换)

Syntax: sub_filter string replacement;

Default: -

Context: http,server,location

语法配置二:(作用:记录是否发生变更,节省不必要的消耗,主要用于缓存的场景)

Syntax: sub_filter_last_modified on | off;

Default: sub_filter_last_modified off;

Context: http,server,location

语法配置三:(作用:替换内容时是只匹配第一个还是所有,on时,只匹配第一个,off时匹配所有)

Syntax: sub_filter_once on | off;

Default: sub_filter_once on;

Context: http,server,location

server {
    ...
    location / {
        root	/opt/app/code;
        index	index.html index.htm;
        sub_filter	'【要替换的内容】' '【替换后的内容】';
        sub_filter_once	off; # 全局替换,替换所有内容
    }
}

Nginx的请求限制

  • 连接频率限制 - limit_conn_module

    • 连接限制:

      Syntax: limit_conn_zone key zone=name:size;

      Default: -

      Context: http

      Syntax: limit_conn zone number;

      Default: -

      Context: http,server,location

  • 请求频率限制 - limit_req_module

    • 请求限制:

      Syntax: limit_req_zone key zone=name:size rate=rate;

      Default: -

      Context: http

      Syntax: limit_req zone=name [burst=number]`[nodelay];

      Default: -

      Context: http,server,location

      	limit_conn_zone $binary_remote_addr zone=conn_zone:1m;
      	#              客户端ip节省空间写法  申请的空间为1M    每秒一个
      	limit_req_zone $binary_remote_addr zone=req_zone:1m rate=1r/s;
      server {
          ...
          location / {
              root	/opt/app/code;
              limit_conn conn_zone 1;
              #limit_req zone=req_zone burst=3 nodelay;
              #limit_req zone=req_zone burst=3;
              #limit_req zone=req_zone; 
              index  index.html index.htm;
          }
      }
      
HTTP协议版本 连接关系
HTTP1.0 TCP不能复用
HTTP1.1 顺序性TCP复用
HTTP2.0 多路复用TCP复用

总结出:

  1. HTTP请求建立在一次TCP连接基础之上
  2. 一次TCP请求至少产生一次HTTP请求

Nginx访问控制

  • 基于IP的访问控制 - http_access_module

    • 配置语法:

      Syntax: allow address | CIDR | unix: | all;

      Default: -

      Context: http,server,location,limit_except

      Syntax: deny address | CIDR | unix: | all;

      Default: -

      Context: http,server,location,limit_except

      server {
          ...
          location / {
              root	/opt/app/code;
              index	index.html index.htm;
          }
          # ~ 的意思时模式匹配 以admin.html开头的 只禁止某个IP
          location ~ ^/admin.html {
              root	/opt/app/code;
              deny	xxx.xxx.xxx.xxx;
              allow	all;
              index	index.html index.htm;
          }
          
          # 只允许某个IP访问
          location ~ ^/admin.html {
              root	/opt/app/code;
              allow	xxx.xxx.xxx.xxx;
              deny	all;
              index	index.html index.htm;
          }
      }
      
    • http_access_module的局限性

      • 如果不是客户端直接访问,而是通过代理的方式来访问remote_addr的值为代理的IP,准确性不高
    • 局限性解决办法

      • 方法一:采用别的HTTP头部信息控制访问,如:HTTP_X_FORWARD_FOR(不靠谱)
      • 方法二:结合geo模块做
      • 方法三:通过HTTP自定义变量传递
  • 基于用户的信任登录 - http_auth_basic_module

    • 配置语法:

      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

      # 安装htpasswd模块
      rpm -qf /usr/bin/htpasswd
      yum install httpd-tools
      
      # 生成密码文件
      htpasswd -c ./auth_conf [用户名] 回车
      New password: [输入密码]
      
      server {
          ...
          location / {
              root	/opt/app/code;
              index	index.html index.htm;
          }
          
          location ~ ^/admin.html {
              root	/opt/app/code;
              auth_basic	"Auth access test! input your passward";
              auth_basic_user_file	/etc/nginx/auth_conf;
              index	index.html index.htm;
          }
      }
      
    • http_auth_basic_module的局限性

      • 用户信息依赖文件方式
      • 操作管理机械,效率低下
    • 解决方案

      • nginx结合lua实现高效验证
      • nginx和LDAP打通,利用nginx-auth-ldap模块

Nginx作为静态资源服务器

静态资源类型

非服务器动态生成的文件

类型 种类
浏览器端渲染 HTML、CSS、JS
图片 JPEG、GIF、PNG
视频 FLV、MPEG
文件 TXT、等任意下载文件

配置语法:

  • 文件读取:

    • Syntax: sendfile on | off;
    • Default: sendfile off;
    • Context: http,server,location,if in location
  • tcp_nopush 作用:sendfile开启的情况下,提高网络包的传输效率(大文件推荐打开)

    • Syntax: tcp_nopush on | off;
    • Default: tcp_nopush off;
    • Context: http,server,location
  • tcp_nodelay 作用:keepalive连接下,提高网络包的传输实时性

    • Syntax: tcp_nodelay on | off;
    • Default: tcp_nodelay on;
    • Context: http,server,location
  • 压缩 作用:压缩传输

    • Syntax: gzip on | off;

    • Default: gizp off;

    • Context: http,server,location,if in location

      压缩比:

    • Syntax: gzip_comp_level level;

    • Default: gzip_comp_level 1;

    • Context: http,server,location

      压缩版本:

    • Syntax: gzip_http_version 1.0 | 1.1;

    • Default: gzip_http_version 1.1;

    • Context: http,server,location

扩展Nginx压缩模块

  • http_gzip_static_module - 预读gzip功能(开启后会读磁盘中的xxx.xxx.gz文件)
  • http_gunzip_module - 应用支持gunzip的压缩方式
server {
	listen       80;
	server_name  116.62.103.228 jeson.example.com;
    
    sendfile on;
    #charset koi8-r;
    access_log  /var/log/nginx/log/static_access.log  main;

    
    location ~ .*\.(jpg|gif|png)$ {
        gzip on;
        gzip_http_version 1.1;
        gzip_comp_level 2;
        gzip_types text/plain application/javascript application/x-javascript text/css application/xml text/javascript application/x-httpd-php image/jpeg image/gif image/png;
        root  /opt/app/code/images;
    }

    location ~ .*\.(txt|xml)$ {
        gzip on;
        gzip_http_version 1.1;
        gzip_comp_level 1;
        gzip_types text/plain application/javascript application/x-javascript text/css application/xml text/javascript application/x-httpd-php image/jpeg image/gif image/png;
        root  /opt/app/code/doc;
    }

    location ~ ^/download {
        gzip_static on;
        tcp_nopush on;
        root /opt/app/code;
    }
}

浏览器缓存原理

HTTP协议定义的缓存机制(如:Expires;Cache-control等)

校验过期机制:

  • 校验是否过期:Expires、Cache-control(max-age)
  • 协议中Etag头信息校验:Etag
  • Last-Modified头部信息校验:Last-Modified

配置语法:expires

​ 原理:添加Cache-control、Expires头

Syntax: expires [modified] time;

​ expires epoch | max | off;

Default: expires off;

Context: http,server,location,if in location

server {
    ...
    location ~ .*\.(htm|html)$ {
        expires 24h;
        root  /opt/app/code;
    }
}

跨站访问

为什么浏览器禁止跨域访问?

​ 不安全,容易出现CSRF攻击!

配置语法:

​ Syntax: add_header name value [always];

​ Default: -

​ Context: http,server,location,if in location

设置完成后,客户端(浏览器)就会去读Access-Control-Allow-Origin头部信息,看是否允许跨站访问

server {
    ...
    location ~ .*\.(htm|html)$ {
        add_header Access-Control-Allow-Origin http://www.xxx.com; # 允许所有 *
        add_header Access-Control-Allow-Methods GET,POST,PUT,DELETE,OPTIONS;
        root  /opt/app/code;
    }
}

防盗链

目的:防止资源被盗用

防盗链设置思路:

​ 首要方式:区别哪些请求时非正常的用户请求

基于http_refer防盗链配置模块

配置语法:

​ Syntax: valid_referers none | blocked | sever_names | string …; 还能支持正则

​ Default: -

​ Context: server,location

server {
    ...
    location ~ .*\.(jpg|gif|png)$ {
    	valid_referers	none blocked xxx.xxx.xxx.xxx;
    	if ($invalid_referer) {
            return 403;
    	}
        root  /opt/app/code/images;
    }
}

Nginx作为代理服务器

正向代理:代理的客户端

反向代理:代理的服务器

配置语法:

​ Syntax: proxy_pass URL;

​ Default: -

​ Context: location,if in location,limit_except

​ URL支持:http://localhost:8080/uri

​ https://192.168.1.1:8000/uri

​ http://unix:/tmp/backend.socket:/uri/

server {
	listen	80;
	server_name	localhost www.xxx.com;
    ...
    location ~ /test_proxy.html$ {
        proxy_pass	http://127.0.0.1:8080; # 将请求转发到8080端口
    }
}

server {
    listen	8080;
    server_name	xxx;
    ...
    location / {
        root	/opt/app/code;
        index	index.html index.htm;
    }
}
server {
    listen	80;
    server_name	localhost www.xxx.com;
    ...
    location / {
        if ($http_x_forwarded_for !~* "^116\.62\.103\.228") {
            return 403;
        }
        root	/opt/app/code;
        index	index.html index.htm;
    }
}

# 服务器228 作为正向代理
server {
    listen	80;
    server_name	localhost www.xxx.com;
    ...
    resolver	8.8.8.8; # DNS解析器
    location / {
        proxy_pass	http://$http_host$request_uri;
    }
}

# 在浏览器设置代理地址为228

缓冲区:

作用:nginx会尽可能的从服务器多缓冲再返回给客户端,减少io的损耗,另外,会消耗内存,内存不够时会存到硬盘里的临时文件,扩展中的参数就是调节的参数

配置语法:

​ Syntax: proxy_buffering on | off;

​ Default: proxy_buffering on;

​ Context: http,server,location

扩展:prixy_buffer_size、proxy_buffers、proxy_busy_buffers_size

跳转重定向:

​ Syntax: proxy_redirect default; proxy_redirect off; proxy_redirect redirect replacement;

​ Default: proxy_redirect default;

​ Context: http,server,location

头信息:

​ Syntax: proxy_set_header field value;

​ Default: proxy_set_header Host $proxy_host;

​ proxy_set_header Connection close;

​ Context: http,server,location

扩展:proxy_hide_header、proxy_set_body

超时:

​ Syntax: proxy_connect_timeout time;

​ Default: proxy_connect_timeout 60s;

​ Context: http,server,location

建立完连接后的另外的两个超时:

扩展:proxy_read_timeout、proxy_send_timeout

真实企业中的案例:

server {
    ...
    location / {
        proxy_pass	http://127.0.0.1:8080;
        proxy_redirect default; # 一般选择默认就可以,除非后端返回301改写地址时

        proxy_set_header Host $http_host;
        proxy_set_header X-Real-IP $remote_addr;

        proxy_connect_timeout 30;
        proxy_send_timeout 60;
        proxy_read_timeout 60;

        proxy_buffer_size 32k;
        proxy_buffering on;
        proxy_buffers 4 128k;
        proxy_busy_buffers_size 256k;
        proxy_max_temp_file_size 256k;
    }
}

server {
    ...
    location / {
        proxy_pass	http://127.0.0.1:8080;
        include	proxy_params; # 抽取为公用的模块命名为proxy_params
    }
}

# 新建proxy_params文件将里边的公用模块抽取出来
proxy_redirect default;

proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;

proxy_connect_timeout 30;
proxy_send_timeout 60;
proxy_read_timeout 60;

proxy_buffer_size 32k;
proxy_buffering on;
proxy_buffers 4 128k;
proxy_busy_buffers_size 256k;
proxy_max_temp_file_size 256k;

更多配置语法

Nginx负载均衡

核心用到的是:proxy_pass和upstream

配置语法:

​ Syntax: upstream name {…};

​ Default: -

​ Context: http

# server1.conf
server {
    listen	8001;
    server_name	localhost;
    ...
    location / {
        root	/opt/app/code1;
        index	index.html index.htm;
    }
}

# server2.conf
server {
    listen	8002;
    server_name	localhost;
    ...
    location / {
        root	/opt/app/code2;
        index	index.html index.htm;
    }
}

# server3.conf
server {
    listen	8003;
    server_name	localhost;
    ...
    location / {
        root	/opt/app/code3;
        index	index.html index.htm;
    }
}

# 负载均衡配置 upstream_test.conf
	upstream xxx {
        server 116.62.103.228:8001;
        server 116.62.103.228:8002;
        server 116.62.103.228:8003;
	}
server {
	listen	80;
	server_name	localhost www.xxx.com;
	...
	location / {
        proxy_pass http://xxx;
        include proxy_params; # 在文件proxy_params里
	}
}

upstream举例

#         这一组虚拟服务的名字
upstream backend {
    server backend1.example.com weight=5; # weight表示这个节点的权重
    server backend2.example.com:8080;
    server unix:/tmp/backend3;
    
    server backend1.example.com:8080 backup; # backup 表示这是一个备份节点
    server backend2.example.com:8080 backup;
}
名词 含义
down 当前的server暂时不参与负载均衡
backup 预留的备份服务器
max_fails 允许请求失败的次数
fail_timeout 经过max_fails失败后,服务暂停的时间
max_conns 限制最大的接收的连接数

一些示例:

upstream xxx {
    server 116.62.103.228:8001 down; # 下线状态
    server 116.62.103.228:8002 backup; # 备用节点,只有所有节点不可用才启用
    server 116.62.103.228:8003 max_fails=1 fail_timeout=10;
}

轮询策略与加权:

名词 含义
轮询 按时间顺序逐一分配到不同的后端服务器
加权轮询 weight值越大,分配到的访问几率越高
ip_hash 每一个请求按访问IP的hash结果分配,这样来自同一个IP的固定访问一个后端服务器
url_hash 按照访问的URL的hash结果来分配请求,使每个URL定向到同一个后端服务器
least_conn 最少链接数,哪个机器连接数少就分发哪个
hash关键数值 hash自定义的key

ip_hash演示:

upstream xxx {
    ip_hash;
    server 116.62.103.228:8001;
    server 116.62.103.228:8002;
    server 116.62.103.228:8003;
}

url_hash演示:

配置语法:

​ Syntax: hash key [consistent]

​ Default: -

​ Context: upstream

​ This directive appeared in version 1.7.2

upstream xxx {
    hash $request_url;
    server 116.62.103.228:8001;
    server 116.62.103.228:8002;
    server 116.62.103.228:8003;
}

Nginx作为缓存服务

proxy_cache配置语法:

# path
Syntax: proxy_cache_path path [levels=levels] [use_temp_path=on | off] keys_zone=name:size [inactive=time] [max_size=size] [manager_files=number] [manager_sleep=time] [manager_threshold=time] [loader_files=number] [loader_sleep=time] [loader_threshold=time] [purger=on | off] [purger_files=number] [purger_sleep=time] [purger_threshold=time];
Default: -
Context: http
# cache
Syntax: proxy_cache zone | off;
Default: proxy_cache off;
Context: http,server,location
# 缓存过期周期配置
Syntax: proxy_cache_valid [code ...] time;
Default: -
Context: http,server,location
# 缓存的维度
Syntax: proxy_cache_key string;
Default: proxy_cache_key $scheme$proxy_host$request_uri;
Context: http,server,location

配置场景:

	upstream example {
        server 116.62.103.228:8001;
        server 116.62.103.228:8002;
        server 116.62.103.228:8003;
    }

    proxy_cache_path /opt/app/cache levels=1:2 keys_zone=example_cache:10m max_size=10g inactive=60m use_temp_path=off;
server {
    listen       80;
    server_name  localhost jeson.t.example.io;

    #charset koi8-r;
    access_log  /var/log/nginx/test_proxy.access.log  main;

    
    location / {
        proxy_cache example_cache;
        proxy_pass http://example;
        proxy_cache_valid 200 304 12h;
        proxy_cache_valid any 10m;
        proxy_cache_key $host$uri$is_args$args;
        add_header  Nginx-Cache "$upstream_cache_status";  
        
        proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504;
        include proxy_params;
    }
}

如何清理指定缓存:

  • 方式一:rm -rf 缓存目录内容
  • 方式二:第三方扩展模块ngx_cache_purge

如何让部分页面不缓存:

​ Syntax: proxy_no_cache string …;

​ Default: -

​ Context: http,server,location

演示:

	upstream example {
        server 116.62.103.228:8001;
        server 116.62.103.228:8002;
        server 116.62.103.228:8003;
    }

    proxy_cache_path /opt/app/cache levels=1:2 keys_zone=example_cache:10m max_size=10g inactive=60m use_temp_path=off;
server {
    listen       80;
    server_name  localhost jeson.t.example.io;

    #charset koi8-r;
    access_log  /var/log/nginx/test_proxy.access.log  main;

    if ($request_uri ~ ^/(url3|login|register|password\/reset)) {
        set $cookie_nochche 1;
    }
    
    location / {
        proxy_cache example_cache;
        proxy_pass http://example;
        proxy_cache_valid 200 304 12h;
        proxy_cache_valid any 10m;
        proxy_cache_key $host$uri$is_args$args;
        
        proxy_no_cache $cookie_nocache $arg_nocache $arg_comment;
        proxy_no_cache $http_pragma $http_authorization;
        
        add_header  Nginx-Cache "$upstream_cache_status";  
        
        proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504;
        include proxy_params;
    }
}

分片请求:

大文件分片请求:

​ Syntax: slice size;

​ Default: slice 0;

​ Context: http,server,location

优势:每个子请求收到的数据都会形成一个独立文件,一个请求断了,其他请求不受影响。

缺点:当文件很大或者slice很小的时候,可能会导致文件描述符耗尽等情况。

作者:大写的先生
来源链接:https://blog.csdn.net/Mark_zhaoyang/article/details/105763999

版权声明:
1、JavaClub(https://www.javaclub.cn)以学习交流为目的,由作者投稿、网友推荐和小编整理收藏优秀的IT技术及相关内容,包括但不限于文字、图片、音频、视频、软件、程序等,其均来自互联网,本站不享有版权,版权归原作者所有。

2、本站提供的内容仅用于个人学习、研究或欣赏,以及其他非商业性或非盈利性用途,但同时应遵守著作权法及其他相关法律的规定,不得侵犯相关权利人及本网站的合法权利。
3、本网站内容原作者如不愿意在本网站刊登内容,请及时通知本站(javaclubcn@163.com),我们将第一时间核实后及时予以删除。


本文链接:https://www.javaclub.cn/server/68407.html

标签: Nginx
分享给朋友: