【LNMP】Nginx防盗链、Nginx访问控制、Nginx解析php相关配置和Nginx代理
一、Nginx防盗链
配置如下,可以和上面的配置结合起来:
vim /usr/local/nginx/conf/vhost/test.com.conf
location ~* ^.+\.(gif|jpg|png|swf|flv|rar|zip|doc|pdf|gz|bz2|jpeg|bmp|xls)$
{
expires 7d;
valid_referers none blocked server_names *.test.com ; //定义白名单
if ($invalid_referer) {
return 403; //如果不匹配则回馈403报错
}
access_log off;
}
再检测并重新加载一下:
/usr/local/nginx/sbin/nginx -t
/usr/local/nginx/sbin/nginx -s reload
再来测试一下:
curl -e "http://www.baidu.com/1.txt" -x127.0.0.1:80 -I test.com/1.gif
curl -e "http://www.test.com/1.txt" -x127.0.0.1:80 -I test.com/1.gif
http://www.baidu.com/1.txt 不匹配 test.com,所以报403
http://www.test.com/1.txt 匹配 test.com ,所以显示200正常
二、Nginx访问控制
需求:访问/admin/目录的请求,只允许某几个IP访问,配置如下:
vim /usr/local/nginx/conf/vhost/test.com.conf
location /admin/
{
allow 172.16.17.71;
allow 127.0.0.1;
deny all;
}
测试一下:
curl -e "http://www.baidu.com/1.txt" -x127.0.0.1:80 -I test.com/admin/
curl -x172.16.17.71:80 -I test.com/admin/
curl -e "http://www.baidu.com/1.txt" -x127.0.0.1:80 -I test.com/1.gif
很明显看出只有这两个IP是允许访问的 ,另一个就报错:
另一种情况:
可以匹配正则
location ~ .*(upload|image)/.*\.php$
{
deny all;
}
测试一下:
结果是upload的被禁止解析了
我们再测试一下没有被限制的txt,结果是可以正常解析的:
看一下日志也可以得到结果:
根据user_agent限制
if ($http_user_agent ~ 'Spider/3.0|YoudaoBot|Tomato')
{
return 403;
}
测试一下:
结果是大写开头的Tonmatoxxx 被限制了,但是小写的没有被限制,这个是严格匹配的:
deny all和return 403效果一样
三、Nginx解析php相关配置
vim /usr/local/nginx/conf/vhost/test.com.conf
配置如下:
location ~ \.php$
{
include fastcgi_params;
fastcgi_pass unix:/tmp/php-fcgi.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME /data/wwwroot/test.com$fastcgi_script_name;
}
fastcgi_pass 用来指定php-fpm监听的地址或者socket
再来新建一个配置文件
vim /data/wwwroot/test.com/3.php
<?php
phpinfo();
在我们没有重新加载配置的前提下,我们先测试一下,是不能解析的:
然后我们重新加载一下配置文件,再测试一下发现已经显示源码,可以正常解析了:
/usr/local/nginx/sbin/nginx -s reload
四、Nginx代理
进入目录新建一个配置文件:
cd /usr/local/nginx/conf/vhost
加入如下内容:
vim proxy.conf
server
{
listen 80;
server_name ask.apelearn.com;
location /
{
proxy_pass http://121.201.9.155/; 定义远程服务器(web)
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
再来检测一下配置和重新加载配置文件:
/usr/local/nginx/sbin/nginx -t
/usr/local/nginx/sbin/nginx -s reload
测试一下服务器可不可以访问ask.apelearn.com网站:
curl -x127.0.0.1:80 ask.apelearn.com/robots.txt
测试结果可以正常访问