功能1:由于在nginx配置中,设置了limit_req的流量限制,导致许多请求返回503错误代码,在限流的条件下,为提高用户体验,希望返回正常Code 200,且返回操作频繁的信息:
location /test { ... limit_req zone=zone_ip_rm burst=1 nodelay; error_page 503 =200 /dealwith_503?callback=$arg_callback; } location /dealwith_503{ set $ret_body '{"code": "V00006","msg": "操作太频繁了,请坐下来喝杯茶。"}'; if ( $arg_callback != "" ) { return 200 'try{$arg_callback($ret_body)}catch(e){}'; } return 200 $ret_body; }
功能2:判断当本地文件不存在时到其他地方访问的修改方法
location /html { if (!-e $request_filename) { proxy_pass http://127.0.0.1:88; //... } }
文件及目录匹配,其中: * -f和!-f用来判断是否存在文件 * -d和!-d用来判断是否存在目录 * -e和!-e用来判断是否存在文件或目录 * -x和!-x用来判断文件是否可执行 样例 : 判断访问的图片是否存在,不存在跳转到另外的域名 location ~* ^.+.(jpg|jpeg|gif|css|png|js|ico|thumb) { root /data/wwwroot/bbs.xxx.com; expires 10d; if (!-e $request_filename) { rewrite ^/data/attachment/forum/(.*)$ http://img.xxx.com/forum/$1 permanent; } }
error_page 404 = @fallback; error_page 500 = @fallback; location @fallback { if ($host ~* "^www\.baidu\.com$") { rewrite ^/(.*)$ http://www.sohu.com/$1 break; #redirect,permanent,last } if ($host ~* "^www\.sina\.com$") { rewrite ^/(.*)$ http://www.sohu.com/$1 break; #redirect,permanent,last } }
功能3:请求nginx,返回页面是来访者的IP
注意:需要nginx支持echo 功能。需要nginx编译安装时添加此第三方扩展包。https://github.com/openresty/echo-nginx-module/archive/v0.60.tar.gz。
server { listen 80 default; server_name _; location /test.html { echo "X-Real-IP: $remote_addr"; echo "<br>"; echo "X-Forwarded-For: $proxy_add_x_forwarded_for"; } }