nginx

2020-12-12  本文已影响0人  挑战_bae7

nginx

1.nginx安装

http://nginx.org/en/linux_packages.html#RHEL-CentOS  参考
cat >> /etc/yum.repos.d/nginx.repo <<EOF
[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
EOF
yum install -y nginx
nginx -V 查看官方安装的包
nginx -t 检查语法
nginx -s reload 重载

2.nginx 配置

[root@localhost ~]# rpm -ql nginx
/etc/logrotate.d/nginx
nginx 安装目录 这个官方的  如果其他源的 没有default
/etc/nginx
/etc/nginx/conf.d
/etc/nginx/conf.d/default.conf
/etc/nginx/nginx.conf
Cgi、Fastcgi、Uwcgi配置⽂文件
/etc/nginx/fastcgi_params
/etc/nginx/scgi_params
/etc/nginx/uwsgi_params

/etc/nginx/koi-utf
/etc/nginx/koi-win
/etc/nginx/mime.types
/etc/nginx/modules
/etc/nginx/win-utf
/etc/sysconfig/nginx
/etc/sysconfig/nginx-debug
/usr/lib/systemd/system/nginx-debug.service
/usr/lib/systemd/system/nginx.service
/usr/lib64/nginx
/usr/lib64/nginx/modules
/usr/libexec/initscripts/legacy-actions/nginx
/usr/libexec/initscripts/legacy-actions/nginx/check-reload
/usr/libexec/initscripts/legacy-actions/nginx/upgrade
/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
Nginx默认站点⽬目录
/usr/share/nginx
/usr/share/nginx/html
/usr/share/nginx/html/50x.html
/usr/share/nginx/html/index.html
nginx 缓存目录
/var/cache/nginx
/var/log/nginx
nginx -V
程序安装⽬目录和路路径
--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_tem
--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
设定Nginx进程启动⽤用户和组(安全)
--user=nginx
--group=nginx
设置额外的参数将被添加到CFLAG
--with-cc-opt
S变量量
--with-ld-opt 设置附加的参数, 链接系统库

3.nginx内置变量

$uri: 当前请求的uri,不不带参数
$request_uri: 请求的uri,带完整参数
$host: http请求报⽂文中host⾸首部,如果没有则以处理理此请求的虚拟主机的主机名代替
$hostname: nginx服务运⾏行行在主机的主机名
$remote_addr: 客户端IP
$remote_port: 客户端端端口
$remote_user: 使⽤用⽤用户认证时客户端⽤用户输⼊入的⽤用户名
$request_filename: ⽤用户请求中的URI经过本地root或alias转换后映射的本地⽂文件路路径
$request_method: 请求⽅方法, GET POST PUT
$server_addr: 服务器器地址
$server_name: 服务器器名称
$server_port: 服务器器端端口
$server_protocol: 服务器器向客户端发送响应时的协议, 如http/1.1 http/1.0
$scheme:在请求中使⽤用scheme, 如http://xxx.com中的http
$http_HEADER: 匹配请求报⽂文中指定的HEADER
$http_host: 匹配请求报⽂文中的host⾸首部
$document_root: 当前请求映射到的root配置

4.nginx 配置文件介绍

1.Main位于nginx.conf配置⽂文件的最⾼高层
2.Main层下可以有Event、HTTP层
3.HTTP层下⾯面有允许有多个Server层, ⽤用于对不同的⽹网站做不同的配置
4.Server层也允许有多个Location, ⽤用于对不同的路路径进⾏行行不同模块的配置

vim /etc/nginx/nginx.conf
user  nginx;
worker_processes  1;  一般跟cpu核数一样
error_log  /var/log/nginx/error.log warn;
pid        /var/run/nginx.pid;
events { //事件模块
worker_connections   1024  //每个worker进程⽀支持的最⼤大连接数 跟上面cpu核数相乘
use   //内核模型,select,poll,epoll 
}

5.nginx 日志管理

curl -I -m 10 -o /dev/null -s -w %{http_code} www.google.com 查看网页状态信息
curl -I   头部信息
[root@localhost ~]# curl -v 127.0.0.1       查看网页信息
* About to connect() to 127.0.0.1 port 80 (#0)
*   Trying 127.0.0.1...
* Connected to 127.0.0.1 (127.0.0.1) port 80 (#0)
> GET / HTTP/1.1
> User-Agent: curl/7.29.0
> Host: 127.0.0.1
> Accept: */*
> 
< HTTP/1.1 200 OK
< Server: nginx/1.18.0
< Date: Fri, 11 Dec 2020 01:16:07 GMT
< Content-Type: text/html
< Content-Length: 612
< Last-Modified: Thu, 29 Oct 2020 15:25:17 GMT
< Connection: keep-alive
< ETag: "5f9adedd-264"
< Accept-Ranges: bytes

    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;
$remote_addr   //表示客户端地址
$remote_user   //http客户端请求nginx认证⽤用户名
$time_local   //Nginx的时间
$request   //Request请求⾏行, GET等⽅方法、http协议版本
$status   //respoence返回状态码
$body_bytes_sent   //从服务端响应给客户端body信息⼤大⼩小
$http_referer   //http上⼀一级页⾯, 防盗链、⽤用户⾏行行为分析
$http_user_agent   //http头部信息, 客户端访问设备
$http_x_forwarded_for   //http请求携带的http信息

6.nginx 状态监控

http://nginx.org/en/docs/http/ngx_http_status_module.html
--with-http_stub_status_module 模块记录 Nginx 客户端基本访问状态信息
在server层中
    location /mystatus {
        stub_status on;  
        access_log off;
    }
access_log off; ##是否写入access日志中
Active connections: 1   当前连接数
server accepts handled requests
 4 4 12 
请求 握手 总共处理请求
Reading: 0 Writing: 1 Waiting: 0 
server表示Nginx处理理接收握⼿手总次数。
accepts表示Nginx处理理接收总连接数。
请求丢失数=(握⼿手数-连接数)可以看出,本次状态显示没有丢失请求。
handled requests,表示总共处理理了了4次请求。
Reading Nginx读取数据
Writing Nginx写的情况
Waiting Nginx开启keep-alive长连接情况下, 既没有读也没有写, 建⽴立连接情况

7.nginx下载站点

Syntax: autoindex on | off;
Default:
autoindex off;
Context: http, server, location
//autoindex常⽤用参数
autoindex_exact_size off;
默认为on, 显示出⽂文件的确切⼤大⼩小,单位是bytes。
修改为off,显示出⽂文件的⼤大概⼤大⼩小,单位是kB或者MB或者GB。
autoindex_localtime on;
默认为off,显示的⽂文件时间为GMT时间。
修改为on, 显示的⽂文件时间为⽂文件的服务器器时间
charset utf-8,gbk;
默认中⽂文⽬目录乱码,添加上解决乱码。
//开启⽬目录浏览
 location / {
        root   /usr/share/nginx/html;
        index  index.html index.htm;
        autoindex on;
        autoindex_localtime on;
        autoindex_exact_size off;
       charset utf-8,gbk;
    }
或者  这种必须/soft/nginx下新建down文件夹 即/soft/nginx/down
location /down {
       root /soft/nginx;
       index index.html;
       autoindex on;
       autoindex_localtime on;
       autoindex_exact_size off;
      charset utf-8,gbk;
    }
或者 这种使用别名的方式 不需要格外创建文件夹
 location /upload {
       alias /soft/nginx;
       index index.html;
       autoindex on;
        autoindex_localtime on;
        autoindex_exact_size off;
        charset utf-8,gbk;
    }

8.nginx 下载限制

请求频率限制 limit_req_module
//Nginx请求限制语法
Syntax: limit_req_zone key zone=name:size rate=rate;
Default: —
Context: http  
Syntax: limit_conn zone number [burst=number] [nodelay];
Default: —
Context: http, server, location

//压⼒测试
yum install -y httpd-tools
ab -n 50 -c 20 http://127.0.0.1/index.html 同时50个连接 并发20个请求

http {
//http段配置请求限制, rate限制速率,限制⼀一秒钟最多⼀一个IP请求  
limit_req_zone $binary_remote_addr zone=req_zone:10m rate=1r/s;
...
location / {
//1r/s只接收⼀一个请求,其余请求拒绝处理理并返回错误码给客户端
limit_req zone=req_zone;
压测结果Complete requests:      50
               Failed requests:        49

//请求超过1r/s,剩下的将被延迟处理理,请求数超过burst定义的数量burst=3, 多余的请求返回503
#limit_req zone=req_zone burst=3 nodelay;
压测结果 Complete requests:      50
               Failed requests:        46

}
连接频率限制 limit_conn_module  无法测试出来
http {
//http段配置连接限制, 同⼀一时刻只允许⼀一个客户端IP连接
limit_conn_zone $binary_remote_addr zone=conn_zone:10m;
...
server {
...
location / {
//同⼀一时刻只允许⼀一个客户端IP连接
limit_conn conn_zone 1;
}
总结:
多个请求可以建⽴立在⼀一次的TCP连接之上, 那么我们对请求的精度限制,当然
⽐比对⼀一个连接的限制会更更加的有效。
因为同⼀一时刻只允许⼀一个连接请求进⼊入。
但是同⼀一时刻多个请求可以通过⼀一个连接进⼊入。
所以请求限制才是比较优的解决⽅方案。(遇到恶意压测的时候 请求限制更优。) 

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

location / {
        root   /usr/share/nginx/html;
        index  index.html index.htm;
        deny 192.168.122.104; 拒绝
        allow all;  允许所有
    }
或
location / {
root html;
index index.php index.html index.htm;
allow 192.168.122.0/24;
deny all;
}
这样自由可以访问状态网页
   location /mystatus {
        stub_status on;  
        access_log off;
       allow 127.0.0.1;
      deny all;
    }
使⽤用 http_x_forwarded_for 记录真实客户端IP地址以及代理理服务器器IP
基于⽤用户登陆认证 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
//需要安装依赖组件
 yum install httpd-tools
htpasswd -c /etc/nginx/auth_conf test    新建用户
htpasswd -b /etc/nginx/auth_conf test1  追加用户
location / {
        root   /usr/share/nginx/html;
        index  index.html index.htm;
        auth_basic "Auth access Blog Input your Passwd!";
        auth_basic_user_file /etc/nginx/auth_conf;
    }
1. Nginx 结合 LUA 实现⾼高效验证
2. Nginx 结合 LDAP 利利⽤用 nginx-auth-ldap 模块

10.Nginx基于域名访问

vim  /etc/nginx/conf.d/www.conf
server {
      listen  80;
     server_name www.test.com;
      root /soft/www/;
      index index.html;
  .....
}
vim  /etc/nginx/conf.d/bbs.conf
server {
      listen  80;
     server_name bbs.test.com bbs1.test.com test4.com; 可以绑定多个域名空格 隔开
      root /soft/bbs/;
      index index.html;
  .....
curl www.test.com
curl bbs.test.com
}
不同的端口 
server {
   listen 8001;
     server_name www.test.com;
      root /soft/www/;
      index index.html;
 ...
}
server {
   listen 8002;
 ...
}
同一个域名指向不同的文件 配置根据ll 谁在前 指向谁 优先读取

11.静态资源的配置方法

1.⽂文件读取⾼高效 sendfile
Syntax: sendfile on | off;
Default: sendfile off;
Context: http, server, location, if in location
2.提⾼高⽹网络传输效率 nopush
Syntax: tcp_nopush on | off;
Default: tcp_nopush off;
Context: http, server, location
作⽤用: sendfile开启情况下, 提⾼高⽹网络包的'传输效率' 可以理解为过一定时间一起传输
3.与 tcp_nopush 之对应的配置 tcp_nodelay
Syntax: tcp_nodelay on | off;
Default: tcp_nodelay on;
Context: http, server, location
作⽤用: 在keepalive连接下,提⾼高⽹网络的传输'实时性'

12.静态资源文件压缩

1.gzip 压缩配置语法
Syntax: gzip on | off;
Default: gzip off;
Context: http, server, location, if in location
2. gzip 压缩⽐比率配置语法
Syntax: gzip_comp_level level;
Default: gzip_comp_level 1;
Context: http, server, location
作⽤用: 压缩本身⽐比较耗费服务端性能
3. gzip 压缩协议版本
Syntax: gzip_http_version 1.0 | 1.1;
Default: gzip_http_version 1.1;
Context: http, server, location
作⽤用: 压缩使⽤用在http哪个协议, 主流版本1.1
4.扩展压缩模块
Syntax: gzip_static on | off | always;
Default: gzip_static off;
Context: http, server, location
作⽤用: 预读gzip功能
图片压缩案例:
[root@localhost conf.d]# vim static.conf 
server {
        listen 80;
        server_name www.test.com;
        sendfile on;
        access_log /var/log/nginx/static_access.log main;
        location ~ .*\.(jpg|gif|png)$ {
        gzip on;
        gzip_http_version 1.1;
        gzip_comp_level 2;
        gzip_types text/plain application/json application/x-javascript application/css application/xml application/xml+rss text/javascript application/x-httpd-php image/jpeg image/gif image/png;
        root /soft/images;
}
}
gzip_types  参考/etc/nginx/mime.types
文件压缩案例:
[root@localhost conf.d]# vim file.conf 
server {
        listen 80;
        server_name www.a.com;
        sendfile on;
        access_log /var/log/nginx/static_access.log main;
        location ~ .*\.(txt|xml)$ {
        gzip on;
        gzip_http_version 1.1;
        gzip_comp_level 1;
        gzip_types text/plain application/json application/x-javascript application/css application/xml application/xml+rss text/javascript application/x-httpd-php image/jpeg image/gif image/png;
        root /soft/doc;
}
}
[root@localhost soft]# ll /soft/images/cs.jpg /soft/doc/m.txt  -h
-rw-rw-rw-. 1  666 root 596K 12月 12 08:32 /soft/doc/m.txt
-rw-r--r--. 1 root root 277K 5月  16 2020 /soft/images/cs.jpg

图片.png
图片.png

13.静态资源浏览器缓存

1.缓存配置语法 expires
Syntax: expires [modified] time;
expires epoch | max | off;
Default: expires off;
Context: http, server, location, if in location
作⽤用: 添加Cache-Control Expires头
2.配置静态资源缓存
location ~ .*\.(js|css|html)$ {
root /soft/code/js;
expires 1h;
}
location ~ .*\.(jpg|gif|png)$ {
root /soft/code/images;
expires 7d;
}

[root@db02 ~]# curl -I www.test.com/test.jpg
HTTP/1.1 200 OK
Server: nginx/1.18.0
Date: Sat, 12 Dec 2020 01:23:53 GMT
Content-Type: image/jpeg
Content-Length: 8122750
Last-Modified: Mon, 18 May 2020 03:17:01 GMT
Connection: keep-alive
ETag: "5ec1fe2d-7bf17e"
Expires: Sat, 19 Dec 2020 01:23:53 GMT
Cache-Control: max-age=604800   604800/60/60/24=7d 这里可以看到缓存的结果
Accept-Ranges: bytes

3.开发代码没有正式上线时, 希望静态⽂文件不被缓存
//取消js css html等静态⽂文件缓存
location ~ .*\.(css|js|swf|json|mp4|htm|html)$ {
add_header Cache-Control no-store;
add_header Pragma no-cache;
}
如果相同的图片没有过缓存期,需要跟换名字重新缓存引用

14.静态资源跨域访问

Syntax: add_header name value [always];
Default: —
Context: http, server, location, if in location
Access-Control-Allow-Origin
实验: 需要本地hosts 文件 www.test.com  www.a.com 解析
vim /soft/images/index.html
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>测试ajax和跨域访问</title>
<script src="http://libs.baidu.com/jquery/2.1.4/jquery.min.js"></script>
</head>
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
type: "GET",
url: "http://www.a.com/index.html",
success: function(data) {
alert("sucess!!!");
},
error: function() {
alert("fail!!,请刷新再试!");
}
});
});
</script>
<body>
<h1>测试跨域访问</h1>
</body>
</html>
默认不支持 跨域访问的 需要在 调用的配置文件中添加允许
vim file.conf
server {
        listen 80;
        server_name www.a.com;
        root /soft/doc;
        sendfile on;
        access_log /var/log/nginx/static_access.log main;
        location ~ .*\.(html|htm)$ {
        add_header Access-Control-Allow-Origin http://www.test.com; 
        add_header Access-Control-Allow-Methods GET,POST,PUT,DELETE,OPTIONS;
        root /soft/doc;
}
} 
就支持跨域访问了

15.nginx 盗链

日志"$http_referer"记录
vim /soft/doc/index.html
<html>
<body style="background-color:red;">
<img src="http://www.a.com/cs.jpg">
</body>
</html>
curl http://www.test.com/ 可以正常访问 默认支持倒链
  location ~ .*\.(jpg|gif|png)$ {
        valid_referers none blocked www.a.com;
        if ($invalid_referer) {
        return 403;
        }
        root /soft/doc;
        }
这限制只能www.a.com访问  也可以下面测试 伪造头部信息
 curl -e "http://www.baidu.com" -I http://www.a.com/cs.jpg

16.nginx 代理

网页代理
[root@localhost conf.d]# vim /etc/nginx/proxy_params 
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 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;
vim web.conf
server {
        listen 88;
     location / {
        proxy_pass http://www.a.com/cs.jpg;
        include proxy_params;
}
}
这样访问 127.0.0.1:88 跳转到http://www.a.com/cs.jpg
nginx 正向代理
vim static.conf
server {
        listen 80;
        server_name www.test.com;
        root /soft/images;
        location ~ .*\.(jpg|gif|png)$ {
        allow 192.168.122.104;
       deny all;
}
}
 cat /etc/nginx/conf.d/zy_proxy.conf
server {
listen 8080;
resolver 233.5.5.5;
location / {
proxy_pass http://$http_host$request_uri;
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;
}
}
这样122.105可以通过网页代理方式连接访问nginx
nginx 反向代理 
代理服务器上
[root@localhost conf.d]# vim fx.conf 
server {
        listen 86;
        #server_name www.b.com;
        index index.html;
        location / {
        proxy_pass http://192.168.122.104;
        include proxy_params;

}
}
web服务器上
vim image.conf
server {
        listen 80;
        #server_name www.b.com;
        root /soft/;
location ~ .*\.(png|jpg|gif)$ {
        gzip on;
        root /soft/image;
}
}
http://192.168.122.103:86/test.jpg

17.nginx负载均衡

准备3台主机
[root@localhost conf.d]# vim /usr/share/nginx/html/index.html 
<html>
<title> db01</title>
<body bgcolor="red">
<h1> db01-192.168.122.103</h1>
</body>
</html>
[root@localhost conf.d]# vim /usr/share/nginx/html/index.html 
<html>
<title> db02</title>
<body bgcolor="blue">
<h1> db02-192.168.122.104</h1>
</body>
</html>
调度
[root@localhost conf.d]# vim proxy.conf 
upstream node {
     server 192.168.122.103;
     server 192.168.122.104;

}

server {

       server_name 192.168.122.105;
       listen 88;
       location / {
          proxy_pass http://node;
         include proxy_params;
}
}
调度状态 是否在线
down 当前的server暂时不参与负载均衡
backup 预留的备份服务器器
max_fails 允许请求失败的次数    请求m次失败 如果超时就清除掉
fail_timeout 经过max_fails失败后, 服务暂停时间
max_conns 限制最⼤大的接收连接数
upstream load_pass {
server 192.168.122.103 down;
server 192.168.122.104 backup;
server 192.168.122.105 max_fails=1 fail_timeout=10s;
}
location / {
proxy_pass http://load_pass;
include proxy_params;
}
调度算法
轮询按时间顺序逐⼀一分配到不不同的后端服务器器(默认)
weight 加权轮询,weight值越⼤大,分配到的访问⼏几率越⾼高
ip_hash 每个请求按访问IP的hash结果分配,这样来⾃自同⼀一IP的固定访问⼀一个后端服务器器
url_hash 按照访问URL的hash结果来分配请求,是每个URL定向到同⼀一个后端服务器器
least_conn 最少链接数,那个机器器链接数少就分发
hash关键数
值hash⾃自定义的key
案例:
Nginx负载均衡权重轮询具体配置
upstream load_pass {
server 192.168.56.11:8001;
server 192.168.56.12:8002 weight=5;
server 192.168.56.13:8003;
}

Nginx负载均衡 ip_hash 具体配置
//如果客户端都⾛走相同代理理, 会导致某⼀一台服务器器连接过多
upstream load_pass {
ip_hash;
server 192.168.56.11:8001;
server 192.168.56.12:8002;
server 192.168.56.13:8003;
}
//如果出现通过代理理访问会影响后端节点接收状态均衡

Nginx负载均衡url_hash具体配置
upstream load_pass {
hash $request_uri;
server 192.168.56.11:8001;
server 192.168.56.12:8002;
server 192.168.56.13:8003;
}

18.nginx tcp 4层代理

必须在main层
vim /etc/nginx/nginx.conf
stream {
upstream ssh_proxy {
hash $remote_addr consistent;
server 192.168.122.103:22;
}

server {
listen 6666;
proxy_connect_timeout 1s;
proxy_timeout 300s;
proxy_pass ssh_proxy;
}
}

19.测试动静分离

2台主机 1 代理  2 安装nginx+tomcat
配置静态资源
wget -O /soft/image/nginx.png http://nginx.org/nginx.png

server {
        listen 80;
        #server_name www.b.com;
        root /soft/;
        location ~ .*\.(png|jpg|gif)$ {
          gzip on;
          root /soft/image;
}
}
curl http://192.168.122.104/nginx.png
配置tomcat
yum install java -y
wget https://mirror.bit.edu.cn/apache/tomcat/tomcat-9/v9.0.41/bin/apache-tomcat-9.0.41.tar.gz
tar xf apache-tomcat-9.0.41.tar.gz -C /soft/tomcat
vi /soft/tomcat/apache-tomcat-9.0.41/webapps/ROOT/java_test.jsp
vi /soft/tomcat/apache-tomcat-9.0.41/webapps/ROOT/java_test.jsp
<HTML>
<HEAD>
<TITLE>JSP Test Page</TITLE>
</HEAD>
<BODY>
<%
Random rand = new Random();
out.println("<h1>Random number:</h1>");
out.println(rand.nextInt(99)+100);
%>
</BODY>
</HTML>
./tomcat/bin/start.sh
curl http://192.168.122.14:8080/java_test.jsp
代理机器
[root@localhost html]# vi /etc/nginx/conf.d/dj.conf 
upstream static {
        server 192.168.122.104:80;
}
upstream java {
        server 192.168.122.104:8080;
}
server {
        listen 83;
        #server_name www.test.com;
        location / {
        root /home/nginx/html;
        index index.html;
}
location ~ .*\.(png|jpg|gif)$ {
        proxy_pass http://static;
        include proxy_params;
}
        location ~ .*\.jsp$ {
        proxy_pass http://java;
        include proxy_params;
}
}
curl http://192.168.122.1/nginx.png
curl http://192.168.122.1/java_test.jsp
测试界面
[root@localhost html]# vim mysite.html 
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>测试ajax和跨域访问</title>
<script src="http://libs.baidu.com/jquery/2.1.4/jquery.min.js"></script>
</head>
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
type: "GET",
url: "http://192.168.122.103/java_test.jsp",
success: function(data) {
$("#get_data").html(data)
},
error: function() {
alert("fail!!,请刷新再试!");
}
});
});
</script>
<body>
<h1>测试动静分离</h1>
<img src="http://192.168.122.103/nginx.png">
<div id="get_data"></div>
</body>
</html>
测试ok  即使停掉NGINX动态内容也正常显示
根据不同浏览器 访问不同界面
//通过浏览器器来分别连接不不同的浏览器器访问不不同的效果。
http {
...
upstream firefox {
server 172.31.57.133:80;
}
upstream chrome {
server 172.31.57.133:8080;
}
upstream iphone {
server 172.31.57.134:8080;
}
upstream android {
server 172.31.57.134:8081;
}
upstream default {
server 172.31.57.134:80;
}
...
}
//server根据判断来访问不不同的⻚页⾯面
server {
listen 80;
server_name www.xuliangwei.com;
#safari浏览器器访问的效果
location / {
if ($http_user_agent ~* "Safari"){
proxy_pass http://dynamic_pools;
}
#firefox浏览器器访问效果
if ($http_user_agent ~* "Firefox"){
proxy_pass http://static_pools;
}
#chrome浏览器器访问效果
if ($http_user_agent ~* "Chrome"){
proxy_pass http://chrome;
}
#iphone⼿手机访问效果
if ($http_user_agent ~* "iphone"){
proxy_pass http://iphone;
}
#android手机访问效果
if ($http_user_agent ~* "android"){
proxy_pass http://and;
}
#其他浏览器器访问默认规则
proxy_pass http://dynamic_pools;
include proxy_params;
}
}
}
例如:

upstream ll {
        server 192.168.122.104:80;
}
upstream ss {
        server 192.168.122.103:80;
}
server {
        listen 82;
        #server_name www.test.com;
        location / {
        if ($http_user_agent ~* "Firefox"){
        proxy_pass http://ss;
        }
        if ($http_user_agent ~* "Chrome"){
        proxy_pass http://ll;
        }
}
}
根据不同目录访问不同服务器
//默认动态,静态直接找设置的static,上传找upload
upstream static_pools {
server 10.0.0.9:80 weight=1;
}
upstream upload_pools {
server 10.0.0.10:80 weight=1;
}
upstream default_pools {
server 10.0.0.9:8080 weight=1;
}
server {
listen 80;
server_name www.xuliangwei.com;
location / {
proxy_pass http://default_pools;
include proxy_params;
}
#url: http://www.xuliangwei.com/static/
location /static/ {
proxy_pass http://static_pools;
include proxy_params;
}
#url: http://www.xuliangwei.com/upload/
location /upload/ {
proxy_pass http://upload_pools;
include proxy_params;
}
}
//⽅方案2:以if语句句实现
if ($request_uri ~* "^/static/(.*)$")
{
proxy_pass http://static_pools/$1;
}
if ($request_uri ~* "^/upload/(.*)$")
{
proxy_pass http://upload_pools/$1;
}
location / {
proxy_pass http://default_pools;
include proxy_params;
}

20.服务器代理缓存

proxy_cache 配置语法
Syntax: proxy_cache zone | off;
Default: proxy_cache off;
Context: http, server, location
//缓存路路径
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
缓存过期周期
Syntax: proxy_cache_valid [code ...] time;
Default: —
Context: http, server, location
//示例
proxy_cache_valid 200 302 10m;
proxy_cache_valid 404 1m;
缓存的维度
Syntax: proxy_cache_key string;
Default: proxy_cache_key $scheme$proxy_host$request_uri;
Context: http, server, location
//示例
proxy_cache_key "$host$request_uri $cookie_user";
proxy_cache_key $scheme$proxy_host$uri$is_args$args;

缓存实战:
两台主机 1台代理 1台后台
后台服务器:
 mkdir /soft/code{1..3}
 for i in {1..3};do echo Code1-Url$i > /soft/code1/url$i.html;done
 for i in {1..3};do echo Code2-Url$i > /soft/code2/url$i.html;done
 for i in {1..3};do echo Code3-Url$i > /soft/code3/url$i.html;done
[root@db02 conf.d]# vim hc.conf 
server {
listen 8081;
root /soft/code1;
index index.html;
}
server {
listen 8082;
root /soft/code2;
index index.html;
}
server {
listen 8083;
root /soft/code3;
index index.html;
}
代理服务器:
mkdir /soft/cache
[root@localhost conf.d]# vim proxy_cache.conf 

upstream cache {
        server 192.168.122.104:8081;
        server 192.168.122.104:8082;
        server 192.168.122.104:8083;
}
proxy_cache_path /soft/cache levels=1:2 keys_zone=code_cache:10m max_size=10g inactive=60m use_temp_path=off;
server {
        listen 89;
        location / {
        proxy_pass http://cache;
        proxy_cache code_cache;
        proxy_cache_valid 200 304 12h;
        proxy_cache_valid any 10m;
        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;
        }
        }
#proxy_cache存放缓存临时⽂文件
#levels 按照两层⽬目录分级
#keys_zone 开辟空间名, 10m:开辟空间⼤大⼩小, 1m可存放8000key
#max_size 控制最⼤大⼤大⼩小, 超过后Nginx会启⽤用淘汰规则
#inactive 60分钟没有被访问缓存会被清理理
#use_temp_path 临时⽂文件, 会影响性能, 建议关闭
#proxy_cache 开启缓存
#proxy_cache_valid 状态码200|304的过期为12h, 其余状态码10分钟过期
#proxy_cache_key 缓存key
#add_header 增加头信息, 观察客户端respoce是否命中
#proxy_next_upstream 出现502-504或错误, 会跳过此台服务器器访问下台
curl -s -I http://192.168.122.103/url3.html|grep "Nginx-Cache"
Nginx-Cache: MISS
curl -s -I http://192.168.122.103/url3.html|grep "Nginx-Cache"
Nginx-Cache: HIT
清理缓存
1.rm -rf /soft/cache/* 删除
2.编译ngx_cache_purge 扩展模块清理
//建⽴立对应⽬目录
[root@proxy ~]# mkdir /soft/src
[root@proxy ~]# cd /soft/src
//下载Nginx包
[root@proxy ~]# wget http://nginx.org/download/nginx-1.12.2.tar.gz
[root@proxy ~]# tar xf nginx-1.12.2.tar.gz
//下载ngx_cache_purge
[root@proxy ~]# wget http://labs.frickle.com/files/ngx_cache_purge-2.3.tar.gz
[root@proxy ~]# tar xf ngx_cache_purge-2.3.tar.gz
//编译Nginx
[root@nginx src]# cd nginx-1.12.2/ && ./configure \
--prefix=/server/nginx --add-module=../ngx_cache_purge-2.3 \
--with-http_stub_status_module --with-http_ssl_module
[root@nginx src]# make && make install
//需要将上⽂文的缓存proxy_cache.conf⽂文件拷⻉贝⾄至源码包中, 并增加如下内容
location ~ /purge(/.*) {
allow 127.0.0.1;
allow 192.168.69.0/24;
deny all;
proxy_cache_purge code_cache $host$1$is_args$args;
}
//检测配置重新加载
[root@nginx conf.d]# /server/nginx/sbin/nginx -t
[root@nginx conf.d]# /server/nginx/sbin/nginx -s reload
http://192.168.122.103/purge/url3.html 清除缓存
部分网页不缓存
vim proxy_cache.conf
upstream cache {
        server 192.168.122.104:8081;
        server 192.168.122.104:8082;
        server 192.168.122.104:8083;
}
proxy_cache_path /soft/cache levels=1:2 keys_zone=code_cache:10m max_size=10g inactive=60m use_temp_path=off;
server {
        listen 89;
        if ($request_uri ~ ^/(url3|login|register|password)) {
        set $cookie_nocache 1;
        }

        location / {
        proxy_pass http://cache;
        proxy_cache code_cache;
        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_pargma $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;
        }
        location ~ /purge(/.*) {
        proxy_cache_purge code_cache $host$1$is_args$args;
        }
        }
curl -I http://192.168.122.103/url3.html 一直是MISS
缓存日志统计
//修改/etc/nginx/nginx.conf中log_format格式
log_format main '$http_user_agent' '$request_uri' '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"' '"$upstream_cache_status"';
//修改proxy_cache.conf, 在server标签新增access⽇日志
access_log /var/log/nginx/proxy_cache.log main;
Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)/url2.html192.168.122.103 - - [14/Dec/2020:14:52:42 +0800] "GET /url2.html HTTP/1.1" 304 0 "-" "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)" "-""HIT"

21.nginx rewrite

使用范围
1.URL访问跳转: ⽀支持开发设计, ⻚页⾯面跳转, 兼容性⽀支持, 展示效果
2.SEO优化: 依赖于url路路径,以便便⽀支持搜索引擎录⼊入
3.维护: 后台维护, 流量量转发等
4.安全: 伪静态,真实动态⻚页⾯面进⾏行行伪装
语法:
Syntax: rewrite regex replacement [flag];
Default: --
Context: server, location, if
//所有请求转发⾄至/pages/maintain.html
rewrite ^(.*)$ /pages/maintain.html break;
表达式
. 匹配除换⾏行行符以外的任意字符
? 重复0次或1次
+ 重复1次或更更多次
* 最少连接数, 那个机器器连接数少就分发
\d 匹配数字
^ 匹配字符串串的开始
$ 匹配字符串串的结尾
{n} 重复n次
{n,} 重复n此或更更多次
[c] 匹配单个字符c
[a-z] 匹配a-z⼩小写字⺟母的任意⼀一个{n}
\ 转义字符
例如:
rewrite index\.php$ /pages/maintain.html break;
() ⽤用于匹配括号之间的内容, 通过$1,$2调⽤用
if ($http_user_agent ~ Chrome){
rewrite ^(.*)$ /chrome/$1 break;
}
正则表达式测试工具
yum install -y pcre-tools
[root@Nginx ~]# pcretest
PCRE version 8.32 2012-11-30
re> /(\d+)\.(\d+)\.(\d+)\.(\d+)/
data> 192.168.56.11
0: 192.168.56.11
1: 192
2: 168
3: 56
4: 11
Rewrite 标记 flag
last 停⽌rewrite检测
break 停⽌rewrite检测
redirect 返回302临时重定向, 地址栏会显示跳转后的地址
permanent 返回301永久重定向, 地址栏会显示跳转后的地址
例如:
[root@localhost conf.d]# vim rewrite.conf 
server {
        listen 84;
        #server_name localhost;
        root /soft/code;
        location ~ ^/break{
        rewrite ^/break /test/ break;
        }
        location ~ ^/last{
        rewrite ^/last /test/ last;
        }
        location /test/{
        default_type application/json;
        return 200 '{"status":"success"}';
        }
}
curl 192.168.122.103:84/break 显示 404 停止匹配 192.168.122.103:84/test目录 没有test目录
curl 192.168.122.103:84/last  显示成功  跳转
last 与 break 对⽐总结:
last会新建⽴立⼀一个请求, 请求域名+/test
break匹配后不不会进⾏行行匹配, 会查找对应root站点⽬目录下包含/test⽬目录
对⽐比flag中 redirect 与 permanent
vim write.conf

server {
        listen 87;
        server_name localhost;
        root /soft/code;
        location ~ ^/ys {
#       rewrite ^/yy http://www.test.com redirect;
        rewrite ^/ys http://www.a.com permanent;
}
}
 redirect 临时跳转
 permanent 永久跳转 即使nginx不运行也有浏览器缓存 自动跳转
跳转其他 用法
ls /soft/code/course/11/22/course_33.html
location / {
rewrite ^/course-(\d+)-(\d+)-(\d+)\.html /course/$1/$2/course_$3.html break;
}
http://192.168.122.103/course-11-22-33.html /course/11/22/course_33.html
匹配浏览器 跳转
if ($http_user_agent ~* Chrome){
rewrite ^/nginx http://kt.xuliangwei.com/index.html redirect;
}

server {
listen 80;
server_name www.bgx.com bgx.com; 
if ($http_host = nginx.org){                                 ##访问nginx.org 变成下面
rewrite (.*) http://www.bgx.com$1;
}
}
//改良版
server {
listen 80;
server_name bgx.com;
rewrite ^ http://www.bgx.com$request_uri?;
}

22.nginx https 配置 ssl

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
苹果要求:
//openssl必须是1.0.2
[root@Nginx ~]# openssl version
OpenSSL 1.0.2k-fips 26 Jan 2017
//nginx必须有ssl模块
[root@Nginx ~]# nginx -V
--with-http_ssl_module
[root@Nginx ~]# mkdir /etc/nginx/ssl_key -p
[root@Nginx ~]# cd /etc/nginx/ssl_key
创建证书
(umask 066;openssl genrsa -out service.key  4096) 
openssl req -new -key service.key -days 365 -out service.csr 
苹果的要求
openssl genrsa -idea -out server.key 2048
openssl req -days 36500 -x509 -sha256 -nodes -newkey rsa:2048 -keyout server.key -out server.crt

[root@localhost conf.d]# vim ssl.conf 
server {
        listen 443 ssl;
        server_name localhost;
        index index.html index.htm;
        #ssl_session_cache share:SSL:10m;
        ssl_session_timeout 10m;
        ssl_certificate ssl_key/server.crt;
        ssl_certificate_key ssl_key/server.key;
        ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4;
        ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
        ssl_prefer_server_ciphers on;
        location / {
        root /soft;
        access_log /var/log/nginx/ssl.log test;
        }
}
server {
        listen 80;
        server_name localhost;
        rewrite ^(.*) https://$server_name$1 redirect;
}
nginx 报错 413 Request Entity Too Large
http {
    include       mime.types;
    default_type  application/octet-stream;
    server_names_hash_bucket_size 128;
    client_header_buffer_size 32k;
    large_client_header_buffers 4 32k;
    client_max_body_size 100m;
    limit_conn_zone $binary_remote_addr zone=one:32k;
    sendfile        on;
    tcp_nopush     on;
    keepalive_timeout  60;
    tcp_nodelay on;
    gzip  on;
    gzip_min_length  1k;
    gzip_buffers     4 16k;
    gzip_http_version 1.0;
    gzip_comp_level 2;
    gzip_types       text/plain application/x-javascript text/css application/xml;
    gzip_vary on;
    log_format  wwwlogs  '$remote_addr - $remote_user [$time_local] $request $status $body_bytes_sent $http_referer $http_user_agent $http_x_forwarded_for';
    #include default.conf;
    include vhost/*.conf;
}
上一篇下一篇

猜你喜欢

热点阅读