docker下nginx自定义日志并限制ip访问

一.Nginx部署

docker-compose.yml

version: '2'
services:
     nginx:
      image: 'nginx:latest'
      restart: always
      container_name: nginx
      ports:
        - '80:80'
        - '443:443'
      volumes:
        - '/app/nginx/conf.d:/etc/nginx/conf.d'
        - '/app/nginx/logs:/etc/nginx/logs'
      command:  nginx -g 'daemon off;'

创建目录:

mkdir -p /app/nginx/logs
mkdir -p /app/nginx/conf.d

conf.d/default.conf配置文件

server {
    listen       80;
    server_name localhost;
    #自定义日志路径,log格式使用main(默认)
    access_log logs/access_service.log main; 
   location / {
       proxy_set_header X-Real-IP $remote_addr;
       proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
       proxy_set_header Host $http_host;
       proxy_pass http://xxx.com;
       client_max_body_size    100m;
      }

     error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }
}

二.限制IP访问

1.查找访问者ip方法:
awk ‘{print $1}’ access_service.log |sort |uniq -c|sort -n

2.配置文件conf.d/default.conf

server {
    listen       80;
    server_name localhost;
    access_log  logs/access_service.log  main; 
     # 将禁止ip放在server级别
      deny 172.20.0.1; 
   location / {
      # 将禁止ip放在location级别
      # deny 172.20.0.1; 
      allow 172.20.0.1;

       proxy_set_header X-Real-IP $remote_addr;
       proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
       proxy_set_header Host $http_host;
       proxy_pass http://test.xylink.cn;
       client_max_body_size    100m;
      }
     error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }
}

限制ip语法:
deny和allow可以应用到http,server,location级别

//屏蔽单个ip访问
deny IP; 
//允许单个ip访问
allow IP; 
//屏蔽所有ip访问
deny all; 
//允许所有ip访问
allow all; 
//屏蔽整个段即从123.0.0.1到123.255.255.254访问的命令
deny 123.0.0.0/8
//屏蔽IP段即从123.45.0.1到123.45.255.254访问的命令
deny 124.45.0.0/16
//屏蔽IP段即从123.45.6.1到123.45.6.254访问的命令
deny 123.45.6.0/24
//如果你想实现这样的应用,除了几个IP外,其他全部拒绝,
//那需要你在guolv_ip.conf中这样写
allow 1.1.1.1; 
allow 1.1.1.2;
deny all; 

你可能感兴趣的:(nginx)