Nginx进阶篇—web模块及proxy代理

Nginx连接状态:

stub_status_module

展示用户和nginx链接数量信息。

查询模块是否安装

nginx -V 2>&1 | grep stub_status --with-http_stub_status_module

启动状态模块:

在Nginx主配置文件下的server模块里添加
vim /etc/nginx/conf.d/default.conf
server {
location /nginx_status {
stub_status;
allow all;
}
重启nginx
systemctl restart nginx

Nginx随机主页:

andom_index_module
将主页设置成随机页面,是一种微调更新机制

启动随机主页:

1、创建主页目录
mkdir /app
2、创建多个主页
touch /app/{blue.html,green.html,red.html,.yellow.html}
在不同的页面书写不同的内容,例如
<html>
<head>
<title>green color</title>
</head>
<body style="background-color:green">
<h1>green color!</h1>
</body>
</html>
3、在Nginx子配置文件下添加
vim /etc/nginx/conf.d/default.conf
server{
location / {
#root   /usr/share/nginx/html;
#index  index.html index.htm;
root /app;
random_index on;
}
}
systemctl restart nginx

Nginx替换模块:

sub_module
目的
网页内容替换
如果我们用模板生成网站的时候,因为疏漏或者别的原因造成代码不如意,但是此时因为文件数量巨大,不方便全部重新生成,那么这个时候我们就可以用此模块来暂时实现纠错。另一方面,我们也可以利用这个实现服务器端文字过滤的效果。

启用替换

vim /etc/nginx/conf.d/default.conf #启动nginx默认页面 这里是打算把Nginx默认页面进行替换
server {  #在server{下面输入
sub_filter nginx 'meinu';
sub_filter_once on;
location / {
root   /usr/share/nginx/html;
index  index.html index.htm;
}
说明:替换模块  将nginx  替换成 meinu 单次替换 开启
systemctl restart nginx
只替换了一处
将单次替换关闭,再次刷新页面,即可看见全文替换。
sub_filter_once off

文件读取原理介绍:

sendfile #nginx默认启用
未使用sendfile() 的传统网络传输过程:
硬盘 >> kernel buffer >> user buffer>> kernel socket buffer >>协议栈
使用 sendfile() 来进行网络传输的过程:
硬盘 >> kernel buffer (快速拷贝到kernelsocket buffer) >>协议栈
sendfile() 不但能减少切换次数而且还能减少拷贝次数。
tcp_nopush
未使用tcp_nopush()网络资源浪费:
应用程序每产生一次操作就会发送一个包,而典型情况下一个包会拥有一个字节的数据以及40个字节长的包头,于是产生4000%的过载,很轻易地就能令网络发生拥塞。同时也浪费资源
使用tcp_nopush()网络传输效率提升:
当包累计到一定大小后再发送。
tcp_nodelay
开启或关闭nginx使用TCP_NODELAY选项的功能。 这个选项仅在将连接转变为长连接的时候才被启用。
TCP_NODELAY是禁用Nagle算法,即数据包立即发送出去。
由于Nagle和DelayedACK的原因,数据包的确认信息需要积攒到两个时才发送,长连接情况下,奇数包会造成延时40ms,所以tcp_nodelay会将ack立刻发出去。 如果不在长连接时,可以关闭此模块,因为ack会被立刻发出去。

启用模块在Nginx主配置文件下

location /video/ {
sendfile        on;
tcp_nopush  on;
tcp_nodelay  on;
}
默认启动,无需验证

Nginx文件压缩

原理介绍

启动该模块,使文件传输前进行压缩,提升传输效率。

模块

ngx_http_gzip_module

启用模块

在Nginx主配置文件下的 http { 在http标签中启动该功能
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;
gzip_static on;
gzip_static on;# nginx对于静态文件的处理模块
systemctl restart nginx

Nginx页面缓存

ngx_http_headers_module
expires起到控制页面缓存的作用,合理的配置expires可以减少很多服务器的请求要配置expires,可以在http段中或者server段中或者location段中加入。
Nginx(expires 缓存减轻服务端压力)
原理介绍
无缓存,每次访问服务器,均是全文传输。
开启缓存可以加速浏览网站。
启用缓存
开启浏览器缓存,浏览页面。(默认)点击F12查看返回状态码
第一次返回状态码200.页面对象全文传输
第二次返回状态304.页面对象部分传输。

开启服务器缓存模块

vim /etc/nginx/conf.d/default.conf
location / {
    root   /usr/share/nginx/html
    index  index.html index.htm;
    expires 24h;
}
再次浏览页面,观察响应头中出现服务器回复的缓存时间
理解nginx服务器启动缓存时间,加速浏览。缺点是时效性降低。

Nginx防盗链

启动a.com防盗链功能,在a网站配置文件location下写
vi /etc/nginx/conf.d/a.com.conf
server {
listen 80;
server_name a.com;
location / {
        root   /a.com;
        index  index.html;
     
        valid_referers none blocked *.a.com;
        if ($invalid_referer) {
            return 403;
        }
    }
这个是禁用所有盗链
如果希望某些网站能够使用(盗链)资源:
生产环境下:
server {
listen 80;
server_name a.com;
      location / {
location ~* \.(gif|jpg|png|bmp)$ {
root /a.com
    valid_referers none blocked  *.qfcloud.top server_names ~tianyun ~\.google\. ~\.baidu\.;
    if ($invalid_referer) {
        return 403;
}
        #rewrite .* http://qfcloud.top/403.jpg;
    }
}
测试环境下:
server {
listen 80;
server_name a.com;
        location / {
valid_referers  none blocked *.a.com server_name ~\.google\.  ~\/baidu\. b.com  192.168.23.*  a.com;
if ($invalid_referer) {
return 403;
}

        root /a.com;
        index index.html;
        access_log  /var/log/nginx/a.com.access.log  main;
        }
}
再次盗链,合法盗链成功。

Nginx访问限制

ngx_http_limit_req_module
网站压测工具
yum install -y httpd-tools
ab -n 100 -c 10 http://域名/
This is ApacheBench, Version 2.3 <$Revision: 1430300 $>
Benchmarking localhost (be patient).....done


Server Software:          nginx/1.12.1
Server Hostname:        tianyun.me
Server Port:                80

Document Path:          /
Document Length:       671 bytes

Concurrency Level:      10
Time taken for tests:    0.006 seconds
Complete requests:      100                 
Failed requests:            99                      失败的请求
   (Connect: 0, Receive: 0, Length: 99, Exceptions: 0)
Write errors:                0
Non-2xx responses:      99                      有问题的相应。
Total transferred:         73273 bytes
HTML transferred:       53834 bytes
Requests per second:  16131.63 [#/sec] (mean)
Time per request:       0.620 [ms] (mean)
Time per request:       0.062 [ms] (mean, across all concurrent requests)
Transfer rate:             11543.10 [Kbytes/sec] received

启动请求频率限制

vim /etc/nginx/nginx.conf
定义
limit_req_zone $binary_remote_addr zone=req_zone:10m rate=1r/s;
限制请求 二进制地址 限制策略的名称 占用10M空间 允许每秒1次请求
引用
limit_req zone=req_zone;
引用 限制策略的名称
http {
    limit_req_zone $binary_remote_addr zone=req_zone:10m rate=1r/s;     定义
以上是在nginx的主配置文件下添加  #nginx.conf


一下是在网站的主配置文件下添加
    server {
        location / {
            root /usr/share/nginx/html;
            index index.html;
            limit_req zone=req_zone;  引用
            #limit_req zone=req_zone burst=5;
            #limit_req zone=req_zone burst=5 nodelay; 
        }
    }
}
引用限制
引用限制,但是令牌桶有5个。有延迟。速度慢
引用限制,但是令牌桶有5个。无延迟。速度快
burst=5 表示最大延迟请求数量不大于5。
如果太过多的请求被限制延迟是不需要的 ,这时需要使用nodelay参数,服务器会立刻返回503状态码。 
其他网站压测工具: Apache-ab,webbench,Apache-Jemeter

Nginx访问控制

基于主机(ip)

module
ngx_http_access_module
Directives
allow
允许某些主机
deny
拒绝某些主机
Syntax:
Syntax: allow address | CIDR | unix: | all;
Context: http, server, location, limit_except
启用控制
限制主机访问
vim /etc/nginx/conf.d/default.conf
server {
  allow 10.18.45.65;
  allow 10.18.45.181;
  deny all;
}

基于用户(username&password)

module
ngx_http_auth_basic_module
Syntax:
方法一
Syntax: auth_basic string | off;
Context: http, server, location, limit_except
方法二
Syntax: auth_basic_user_file file;
Context: http, server, location, limit_except

启用控制

建立认证文件
yum install -y httpd-tools
htpasswd -cm /etc/nginx/conf.d/passwd user10  #会话密码
如果目录下已经有文件了,那么就不用加-c了,直接-m
htpasswd -m /etc/nginx/conf.d/passwd user20  #会话密码
cat /etc/nginx/conf.d/passwd
观察口令文件是否生成。已生成
user10:$apr1$UE/tLtDM$nVm686kAMYb/ArqQDUi8U/
user20:$apr1$bmn0E/gK$enkXKb2V5uFvUy9wdIHlP.

启动认证

vim /etc/nginx/conf.d/default.conf
server {   找到server{字段,在下一行插入认证字段。
            auth_basic "nginx access test!";
            auth_basic_user_file /etc/nginx/conf.d/passwd;    #提示消息   #引用认证文件
systemctl restart nginx #重启认证

Nginx代理

在代理服务器下/etc/nginx/conf.d/default.conf下添加
location / {
        #root   /usr/share/nginx/html;
        #index  index.html index.htm;
        proxy_pass http://192.168.23.6:80;
        proxy_redirect default;

        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 120s;
        proxy_send_timeout 60s;
        proxy_read_timeout 60s;

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

模块介绍

proxy_pass :真实服务器
proxy_redirect :如果真实服务器使用的是的真是IP:非默认端口。则改成IP:默认端口。
proxy_set_header:重新定义或者添加发往后端服务器的请求头
proxy_set_header X-Real-IP :启用客户端真实地址(否则日志中显示的是代理在访问网站)
proxy_set_header X-Forwarded-For:记录代理地址
proxy_connect_timeout::后端服务器连接的超时时间_发起三次握手等候响应超时时间
proxy_send_timeout:后端服务器数据回传时间_就是在规定时间之内后端服务器必须传完所有的数据
proxy_read_timeout :nginx接收upstream(上游/真实) server数据超时, 默认60s, 如果连续的60s内没有收到1个字节, 连接关闭。像长连接
proxy_buffering on;开启缓存
proxy_buffer_size:proxy_buffer_size只是响应头的缓冲区
proxy_buffers 4 128k; 内容缓冲区域大小
proxy_busy_buffers_size 256k; 从proxy_buffers划出一部分缓冲区来专门向客户端传送数据的地方
proxy_max_temp_file_size 256k;超大的响应头存储成文件。

Nginx代理缓存

启动代理缓存

在代理服务器下/etc/nginx/nginx.conf下添加
http {
 proxy_cache_path /app/hqd/cache levels=1:2 keys_zone=proxy_cache:10m max_size=10g inactive=60m use_temp_path=off;    
在代理服务器下/etc/nginx/conf.d/default.conf
location模块下添加
proxy_cache proxy_cache;         Proxy_cache   使用名为 的对应缓存配置
proxy_cache_valid 200 304 12h;   proxy_cache_valid  200 206 304 301 302 12h; 对httpcode为200…的缓存12小时
proxy_cache_valid any 10m;    proxy_cache_valid 设置不同相应码的缓存时间,除了上面的,其他的的存10分钟
proxy_cache_key $host$uri$is_args$args;  proxy_cache_key $uri  定义缓存唯一key,通过唯一key来进行hash存取
add_header  Nginx-Cache "$upstream_cache_status";   add_header:缓存命中情况如何在http头中体现,以及在nginx日志中查看  proxy_cache_path 缓存文件路径
proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504;   proxy_next_upstream 出现502-504或错误,会跳过此台服务器访问下一台服务器
mkdir -p /app/hqd/cache 准备缓存文件的存放目录
posted @ 2022-09-19 15:34  我真的兔了  阅读(89)  评论(0编辑  收藏  举报