本文共 2201 字,大约阅读时间需要 7 分钟。
防止网站资源被非法引用是每个网站管理员的重要任务之一。Nginx提供了一种简单有效的防盗链解决方案,以下是详细的配置步骤。
编辑虚拟主机文件/usr/local/nginx/conf/vhost/test.com.conf
,在location
块中添加以下配置:
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; } access_log off;}
执行以下命令确保配置无误并重新加载:
/usr/local/nginx/sbin/nginx -t/usr/local/nginx/sbin/nginx -s reload
使用curl
命令测试引用的效果:
curl -e "http://www.baidu.com/123.txt" -x127.0.0.1:80 -I test.com/test.jpg
若返回403 Forbidden,说明防盗链配置成功。
###需求仅允许特定IP访问/admin/
目录,防止一句话木马攻击。
###配置步骤
编辑虚拟主机文件/usr/local/nginx/conf/vhost/test.com.conf
,添加以下配置:
location /admin/ { allow 192.168.248.129; # 允许特定IP访问 allow 127.0.0.1; # 允许本地访问 deny all; # 否则拒绝访问}
allow
和deny
规则按顺序执行,allow
优先于deny
。在Windows机器中:
iptables -I INPUT -p tcp --dport 80 -j ACCEPT
使用浏览器访问http://test.com/admin/
,若未授权IP访问将返回403 Forbidden。
查看Nginx日志:cat /tmp/test.com.log
,确认被拒绝访问的IP地址。
编辑虚拟主机文件/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;}
执行以下命令:
/usr/local/nginx/sbin/nginx -t/usr/local/nginx/sbin/nginx -s reload
使用curl
测试:
curl -x127.0.0.1:80 test.com/test0816.php
若返回502 Bad Gateway,需检查php-fpm
配置文件/etc/php-fpm.conf
,确保listen
设置正确。
进入/usr/local/nginx/conf/vhost/
目录,创建新文件proxy.conf
:
server { listen 80; server_name ask.apelearn.com; location / { proxy_pass http://223.94.95.10/; 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 -tusr/local/nginx/sbin/nginx -s reload
使用curl
命令测试:
curl -x127.0.0.1:80 ask.apelearn.com/robots.txt
php-fpm
服务正常运行。nginx
错误日志:tail -f /tmp/nginx.log
。location
块的匹配顺序至关重要,^~
优先于~*
,.*
优先于.*.(ext)
。
转载地址:http://eyufk.baihongyu.com/