nginx配置(反向代理、限速、url重写)

nginx反向代理

正向代理:代理用户上网,当多个用户访问一个网站时,服务器只需要缓存一份即可
反向代理:代理服务器,以虚拟主机方式,一个ip对应多个主机
应用场景:堡垒机场景,内网服务器发布场景,缓存场景
CDN缓存服务器:缓存静态数据,动态请求由缓存服务器当代理服务器向业务服务器拿,减小业务服务器压力

代理服务器实现

location / {
    proxy_pass http://139.199.32.236:8080
}

使用proxy_pass字段,后面是业务服务器.
每次访问服务器根目录时,自动找业务服务器获取数据

其他字段

请求头,业务服务器可以从代理服务器上看到客户端信息

nginx限速

保护磁盘IO

限速原理

缓存请求、匀速处理、多余请求直接丢弃

限速实现

limit_req_zone:用来限制单位时间内的请求数,即速率限制
limit_req_conn:用来限制同一时间连接数,即并发限制

代码

1.limit_req_zone 限制请求数
limit_req_zone 限制请求数(限速)
limit_req_conn 限制连接数(访问数) 并发数

2.限制下载个数和下载速度

limit_req_zone $binary_remote_addr zone=baism:10m rate=1r/s;
limit_conn_zone $binary_remote_addr zone=addr:10m;
server {
    listen 80;
	server name localhost;
	location / {
	    root html;
		index index.html index.htm	
	}
	location /abc {
		limit_req zone=baism burst=5 nodelay;
		limit_conn addr 1;
		limit_rate 100k;
		limit_rate_after 100m;
	}
}

请求数不能超过1个
下载到100m就会限速到100kb/s
limit_conn_zone; 设置桶
limit_conn addr 1;设置连接数
limit_rate 100k; 设置下载速率

nginx限速

保护磁盘IO

限速原理

缓存请求、匀速处理、多余请求直接丢弃

限速实现

limit_req_zone:用来限制单位时间内的请求数,即速率限制
limit_req_conn:用来限制同一时间连接数,即并发限制

代码

1.limit_req_zone 限制请求数
limit_req_zone 限制请求数(限速)
limit_req_conn 限制连接数(访问数) 并发数

2.限制下载个数和下载速度

limit_req_zone $binary_remote_addr zone=baism:10m rate=1r/s;
limit_conn_zone $binary_remote_addr zone=addr:10m;
server {
    listen 80;
	server name localhost;
	location / {
	    root html;
		index index.html index.htm	
	}
	location /abc {
		limit_req zone=baism burst=5 nodelay;
		limit_conn addr 1;
		limit_rate 100k;
		limit_rate_after 100m;
	}
}

请求数不能超过1个
下载到100m就会限速到100kb/s
limit_conn_zone; 设置桶
limit_conn addr 1;设置连接数
limit_rate 100k; 设置下载速率

nginx实现url重写rewrite

将用户在地址栏输入的地址重新编辑。
作用场景:域名变更、用户跳转、伪静态场景

重写指令

代码1

location /baism00 {
	rewrite ^(.*)$ http://192.168.10.129;
}

location /baism01 {
	rewrite ^(.*)$ http://192.168.10.129 break;
}

location /baism02 {
	rewrite ^(.*)$ http://192.168.10.129 redirect;
}

location /baism03 {
	rewrite ^(.*)$ http://192.168.10.129 permanent;
}

重写规则:rewrite 正则 替代内容 flag标记
flag标记

  • last:匹配后,进行向下执行后面的代码,不跳转
  • break:匹配后中止,不执行后面代码
  • redirect: 302临时重定向 搜索网站保存旧网站
  • permanent:301永久重定向 搜索网站保存新网站

使用正则匹配,注意rewrite匹配字符是 目录全部内容,不是location匹配后剩下的内容

代码2

location /html {
      rewrite /html/(.*)$ /post/$1 permanent;
}   

rewrite 匹配内容 替换内容
匹配内容使用括号分组匹配
替换内容使用$1,$2代表匹配的内容

代码3

location / {
    root html;
    index index.html index.html;
    if ($http_user_agent ~* 'Chrome') {
        break;
        return 43;
        #return http://www.jd.com
    }
}

nginx匹配
模糊匹配:~匹配 !~不匹配 ~*不区分大小写的匹配
精确匹配 :=匹配 !=不匹配
注意:if和()和{}之间都有空格
#注释
$http_user_agent 用户代理,用户浏览器类型
$request_filename 当前请求的文件路径名,由root或alias指令与URL请求生成
$uri 请求的不带请求参数的URL,可能和最初的值有不同,比如经过重定向之类的
$http_host http 地址

原创文章 88 获赞 66 访问量 6万+

猜你喜欢

转载自blog.csdn.net/xgy123xx/article/details/104441324