date: 2020-12-10title: nginx常用配置 #标题
tags: nginx #标签
categories: nginx # 分类

用于记录下nginx常用配置字段。

location匹配某些路径后进行重写

需求:
源地址:http://www.baidu.com/act/actuatorhttp://www.baidu.com/cnt/actuator和http://www.baidu.com/awx/actuator ,匹配到这些源地址后,跳转至 http://www.baidu.com/404.html

对应location如下:

  1. location ~ /(act|cnt|awx)/actuator$ {
  2. rewrite ^/ http://www.baidu.com/404.html;
  3. }

http自动跳转https

  1. server {
  2. listen 80;
  3. server_name localhost;
  4. rewrite ^(.*)$ https://$host$1 permanent;
  5. }

开启gzip压缩

  1. gzip on;
  2. gzip_min_length 10k;
  3. gzip_comp_level 5;
  4. gzip_buffers 4 16k;
  5. gzip_types text/plain application/javascript application/x-javascript text/javascript text/xml text/css text/js application/json;
  6. gzip_http_version 1.1;
  7. gzip_proxied any;
  8. gzip_vary on;
  9. gzip_disable "MSIE [1-6].";

为选定的客户端连接启用调试日志

为选定的客户端连接启用调试日志。其他连接将使用error_log指令设置的日志记录级别 。调试连接由IPv4或IPv6地址或网络指定。也可以使用主机名指定连接。

此功能需编译时增加 “ —with-debug ” 选项。

  1. # 以下示例源于官网
  2. events {
  3. debug_connection 127.0.0.1;
  4. debug_connection localhost;
  5. debug_connection 192.0.2.0/24;
  6. debug_connection ::1;
  7. debug_connection 2001:0db8::/32;
  8. debug_connection unix:;
  9. ...
  10. }

error_log 等级

debug, info, notice, warn, error, crit, alert, emerg。

默认值: error。表示error, crit, alert, emerg级别的日志都记录。

限制请求方法

  1. location / {
  2. limit_except PUT POST GET {
  3. allow 192.168.20.0/24;
  4. deny all;
  5. }
  6. }
  7. # 只能配置在location字段
  8. # 上述配置表示只接受PUT、POST、GET、HEAD请求方法(允许GET会使HEAD也被允许)
  9. # 但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的连接数以及虚拟主机的总连接数

  1. limit_conn_zone $binary_remote_addr zone=perip:10m;
  2. limit_conn_zone $server_name zone=perserver:10m;
  3. server {
  4. ...
  5. limit_conn perip 5;
  6. limit_conn perserver 10000;
  7. }

limit_req_zone

限制来自单个IP地址的请求处理速度,同时限制虚拟服务器的请求速度。

  1. limit_req_zone $binary_remote_addr zone=perip:10m rate=1r/s;
  2. limit_req_zone $server_name zone=perserver:10m rate=10r/s;
  3. server {
  4. ...
  5. limit_req zone=perip burst=5 nodelay;
  6. limit_req zone=perserver burst=10;
  7. }

配置IP鉴权

nginx配置文件如下

  1. http {
  2. ..........
  3. geo $remote_addr $ip_whitelist {
  4. default 0;
  5. include ip_white.conf; # 加载当前目录下的IP白名单列表
  6. }
  7. server {
  8. .........
  9. if ($ip_whitelist = 0) {
  10. return 403;
  11. }
  12. }
  13. }

白名单ip_white.conf文件内容如下

  1. $ cat ip_white.conf
  2. 221.181.101.37 1;
  3. 121.35.180.160 1;
  4. 115.182.250.160/27 1;
  5. 115.182.202.0/26 1;
  6. 223.72.210.192/29 1;
  7. 218.241.193.64/27 1;
  8. 218.205.209.56/30 1;
  9. 223.71.234.8/29 1;
  10. 223.71.234.0/30 1;
  11. 124.192.146.0/24 1;
  12. 172.18.11.0/24 1;
  13. 10.2.5.127 1;
  14. 211.137.112.163 1;
  15. # 此文件内都是允许访问的,可以是IP,也可以是网段。