如果只是针对nginx下的某一个域名进行访问的白名单限制,那么可以在nginx的配置文件里进行设置,利用$remote_addr参数进行访问的分发限制,如下:
[root@china vhosts]# cat testwww.wangshibo.com.conf
server {
listen 80;
server_name testwww.wangshibo.com;
root /var/www/vhosts/testwww.wangshibo.com/httpdocs/main;
access_log /var/www/vhosts/testwww.wangshibo.com/logs/access.log main;
error_log /var/www/vhosts/testwww.wangshibo.com/logs/error.log;
##白名单设置,只允许下面三个来源ip的客户端以及本地能访问该站。主要是下面这三行
if ($remote_addr !~ ^(100.110.15.16|100.110.15.17|100.110.15.18|127.0.0.1)) {
rewrite ^.*$ /maintence.php last;
}
location / {
try_files $uri $uri/ @router;
index index.php;
}
error_page 500 502 503 504 /50x.html;
location @router {
rewrite ^.*$ /index.php last;
}
location ~ \.php$ {
fastcgi_pass 127.0.0.1:9001;
fastcgi_read_timeout 30;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;
#include fastcgi_params;
include fastcgi.conf;
}
}
错误页面内容设置:
[root@china vhosts]# cat /var/www/vhosts/testwww.wangshibo.com/main/maintence.html
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
</head>
<body>
网站临时维护中,请稍后访问...
</body>
</html>
也可以使用$http_x_forwarded_for参数进行访问的分发限制,如下:
server {
listen 80;
server_name testwww.wangshibo.com;
root /var/www/vhosts/testwww.wangshibo.com/httpdocs/main;
access_log /var/www/vhosts/testwww.wangshibo.com/logs/access.log main;
error_log /var/www/vhosts/testwww.wangshibo.com/logs/error.log;
##白名单设置,只允许下面三个来源ip的客户端以及本地能访问该站。
if ($http_x_forwarded_for !~ ^(100.110.15.16|100.110.15.17|100.110.15.18|127.0.0.1)) {
rewrite ^.*$ /maintence.php last;
}
location / {
try_files $uri $uri/ @router;
index index.php;
}
error_page 500 502 503 504 /50x.html;
location @router {
rewrite ^.*$ /index.php last;
}
location ~ \.php$ {
fastcgi_pass 127.0.0.1:9001;
fastcgi_read_timeout 30;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;
#include fastcgi_params;
include fastcgi.conf;
}
}
还可以利用nginx的allow、deny参数进行访问限制
[root@china vhosts]# cat testwww.wangshibo.com.conf
server {
listen 80;
server_name testwww.wangshibo.com;
root /var/www/vhosts/testwww.wangshibo.com/httpdocs/main;
access_log /var/www/vhosts/testwww.wangshibo.com/logs/access.log main;
error_log /var/www/vhosts/testwww.wangshibo.com/logs/error.log;
##白名单设置,只允许下面三个来源ip的客户端以及本地能访问该站。
allow 100.110.15.16;
allow 100.110.15.17;
allow 100.110.15.18;
allow 127.0.0.1;
deny all;
location / {
try_files $uri $uri/ @router;
index index.php;
}
error_page 500 502 503 504 /50x.html;
location @router {
rewrite ^.*$ /index.php last;
}
location ~ \.php$ {
fastcgi_pass 127.0.0.1:9001;
fastcgi_read_timeout 30;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;
#include fastcgi_params;
include fastcgi.conf;
}
}