nginx针对某个url限制ip访问,常用于后台访问限制
nginx针对某个url限制ip访问,常用于后台访问限制
假如我的站点后台地址为: http://www.abc.net/admin.php 那么我想限制只有个别ip可以访问后台,那么需要在配置文件中增加: location ~ .*admin.* { allow 1.1.1.1; allow 12.12.12.0/24; deny all; location ~ \.php$ { include fastcgi_params; fastcgi_pass unix:/tmp/php-fcgi.sock; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME /data/www$fastcgi_script_name; } } 需要注意的是,在这个location下也得加入php解析相关的配置,否则php文件无法解析。
upstream market-api{ server 127.0.0.1:3000; } server { listen 80; listen 443 ssl; server_name btc.btc.com; add_header Access-Control-Allow-Origin *; ssl_certificate /etc/nginx/cert_sql/15.pem; ssl_certificate_key /etc/nginx/cert_sql/15.key; ssl_session_timeout 5m; ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4; ssl_protocols TLSv1 TLSv1.1 TLSv1.2; ssl_prefer_server_ciphers on; #root /var/www/api2; root /var/www/apis; index index.php index.html index.htm; location / { try_files $uri $uri/ =404; } location /apis/{ proxy_pass http://market-api; proxy_set_header Host $host; } location /api/ { if ( !-e $request_filename){ rewrite ^/(.*)$ /api/web/index.php?s=$1 last; } } location ^~ /res/ { alias /data/api/; } include fastcgi-php.conf; }
location ~ .*index.php* { allow 12.12.12.0/24; deny all; location ~ \.php$ { include fastcgi_params; fastcgi_intercept_errors on; fastcgi_pass unix:/var/run/php/php5.6-fpm.sock; fastcgi_param SCRIPT_FILENAME $document_root/$fastcgi_script_name; } }
Nginx配置location限制IP访问策略
1.配置如下
server { listen 80; server_name localhost; large_client_header_buffers 4 16k; client_max_body_size 300m; client_body_buffer_size 128k; proxy_connect_timeout 600; proxy_read_timeout 600; proxy_send_timeout 600; proxy_buffer_size 64k; proxy_buffers 4 32k; proxy_busy_buffers_size 64k; proxy_temp_file_write_size 64k; location / { root html; index index.html index.htm; } location /project { allow 220.178.25.22; allow 172.2.2.0/24; allow 192.2.2.0/24; deny all; proxy_pass http://172.2.2.20:8080/project/; proxy_set_header Host $host:$server_port; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; client_max_body_size 10m; } error_page 500 502 503 504 /50x.html; location = /50x.html { root html; } }
2.配置说明
以上配置的作用是允许IP为220.178.25.22,以及172和192网段的机器可以访问这个location地址,其他IP的客户端访问均是403。
其中,24是指子网掩码为255.255.255.0。
3.对照表(子网掩码/CIDR值)
255.0.0.0/8 255.128.0./9 255.192.0./10 255.224.0./11 255.240.0./12 255.248.0./13 255.252.0./14 255.254.0./15 255.255.0./16 255.255.128/17 255.255.192/18 255.255.224/19 255.255.240/20 255.255.248/21 255.255.252/22 255.255.254/23 255.255.255/24 255.255.255.128/25 255.255.255.192/26 255.255.255.224/27 255.255.255.240/28 255.255.255.248/29 255.255.255.252/30