date: 2020-12-10title: nginx常用配置 #标题
tags: nginx #标签
categories: nginx # 分类
location匹配某些路径后进行重写
需求:
源地址:http://www.baidu.com/act/actuator 、http://www.baidu.com/cnt/actuator和http://www.baidu.com/awx/actuator ,匹配到这些源地址后,跳转至 http://www.baidu.com/404.html
对应location如下:
location ~ /(act|cnt|awx)/actuator$ {
rewrite ^/ http://www.baidu.com/404.html;
}
http自动跳转https
server {
listen 80;
server_name localhost;
rewrite ^(.*)$ https://$host$1 permanent;
}
开启gzip压缩
gzip on;
gzip_min_length 10k;
gzip_comp_level 5;
gzip_buffers 4 16k;
gzip_types text/plain application/javascript application/x-javascript text/javascript text/xml text/css text/js application/json;
gzip_http_version 1.1;
gzip_proxied any;
gzip_vary on;
gzip_disable "MSIE [1-6].";
为选定的客户端连接启用调试日志
为选定的客户端连接启用调试日志。其他连接将使用error_log指令设置的日志记录级别 。调试连接由IPv4或IPv6地址或网络指定。也可以使用主机名指定连接。
此功能需编译时增加 “ —with-debug ” 选项。
# 以下示例源于官网
events {
debug_connection 127.0.0.1;
debug_connection localhost;
debug_connection 192.0.2.0/24;
debug_connection ::1;
debug_connection 2001:0db8::/32;
debug_connection unix:;
...
}
error_log 等级
debug, info, notice, warn, error, crit, alert, emerg。
默认值: error。表示error, crit, alert, emerg级别的日志都记录。
限制请求方法
location / {
limit_except PUT POST GET {
allow 192.168.20.0/24;
deny all;
}
}
# 只能配置在location字段
# 上述配置表示只接受PUT、POST、GET、HEAD请求方法(允许GET会使HEAD也被允许)
# 但192.168.20.0/24 的所有请求方法都接受,除此之外,其他请求方法将返回 403
http常见请求方法有: GET, HEAD, POST, PUT, DELETE, MKCOL, COPY, MOVE, OPTIONS, PROPFIND, PROPPATCH, LOCK, UNLOCK, PATCH。
limit_conn_zone
限制单个client IP的连接数以及虚拟主机的总连接数
limit_conn_zone $binary_remote_addr zone=perip:10m;
limit_conn_zone $server_name zone=perserver:10m;
server {
...
limit_conn perip 5;
limit_conn perserver 10000;
}
limit_req_zone
限制来自单个IP地址的请求处理速度,同时限制虚拟服务器的请求速度。
limit_req_zone $binary_remote_addr zone=perip:10m rate=1r/s;
limit_req_zone $server_name zone=perserver:10m rate=10r/s;
server {
...
limit_req zone=perip burst=5 nodelay;
limit_req zone=perserver burst=10;
}
配置IP鉴权
nginx配置文件如下
http {
..........
geo $remote_addr $ip_whitelist {
default 0;
include ip_white.conf; # 加载当前目录下的IP白名单列表
}
server {
.........
if ($ip_whitelist = 0) {
return 403;
}
}
}
白名单ip_white.conf文件内容如下
$ cat ip_white.conf
221.181.101.37 1;
121.35.180.160 1;
115.182.250.160/27 1;
115.182.202.0/26 1;
223.72.210.192/29 1;
218.241.193.64/27 1;
218.205.209.56/30 1;
223.71.234.8/29 1;
223.71.234.0/30 1;
124.192.146.0/24 1;
172.18.11.0/24 1;
10.2.5.127 1;
211.137.112.163 1;
# 此文件内都是允许访问的,可以是IP,也可以是网段。