本文環(huán)境基于Ubuntu1604
nginx installation
sudo apt install -y nginx
sudo vim /etc/nginx/sites-enabled/site.conf
server {
listen 80;
server_name site.com;
location /a {
alias /tmp;
index a.html;
}
location /b {
alias /tmp;
index b.html;
}
}
echo 'a' >> /tmp/a.html
echo 'b' >> /tmp/b.html
sudo nginx -t
sudo nginx -s reload
sudo sh -c "echo '127.0.0.1 site.com' >> /etc/hosts"
# 在本地訪(fǎng)問(wèn)該服務(wù)
curl -L site.com/a # a
curl -L site.com/b # b
ngx_http_geo_module
nginx -V | grep geo # nginx內(nèi)置geo模塊 --with-http_geoip_module
# $remote_addr 是Nginx內(nèi)置變量 表示客戶(hù)端IP地址
# $ip_whitelist 表示自定義變量
# default 0; 表示自定義變量默認(rèn)值
# 127.0.0.1 1; 表示客戶(hù)端IP地址與給定IP匹配時(shí)自定義變量的值
geo $remote_addr $ip_whitelist {
default 0;
127.0.0.1 1;
}
sudo vim /etc/nginx/sites-enabled/site.conf
geo $remote_addr $ip_whitelist {
default 0;
127.0.0.1 1;
}
server {
listen 80;
server_name site.com;
location /a {
alias /tmp;
index a.html;
}
location /b {
if ($ip_whitelist = 0) {
return 403;
}
alias /tmp;
index b.html;
}
}
sudo nginx -t
sudo nginx -s reload
# 在本地訪(fǎng)問(wèn)該服務(wù)
curl -L site.com/a # a
curl -L site.com/b # b
sudo sh -c "echo '192.168.56.222 site.com' >> /etc/hosts"
# 在其他訪(fǎng)問(wèn)該服務(wù)
curl -L site.com/a # a
curl -L site.com/b # 403 Forbidden