在LNMP(Linux, Nginx, MySQL, PHP)环境中,配置Nginx防盗链主要是为了防止其他网站直接链接到你的图片、视频等资源文件,从而节省带宽和保护资源。以下是配置Nginx防盗链的步骤:
打开Nginx配置文件:
通常位于/etc/nginx/nginx.conf
或/etc/nginx/sites-available/your_domain.conf
。使用文本编辑器打开,例如:sudo nano /etc/nginx/sites-available/your_domain.conf
。
在server
块中添加以下配置:
location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
valid_referers none blocked your_domain.com www.your_domain.com;
if ($invalid_referer) {
rewrite ^/ - [R=403,L];
}
}
这里的your_domain.com
和www.your_domain.com
需要替换成你的实际域名。valid_referers
指令用于设置允许的引用来源,none
表示不允许任何引用,blocked
表示允许被Nginx阻止的引用(例如恶意爬虫),your_domain.com
和www.your_domain.com
表示允许你的域名和子域名访问。if ($invalid_referer)
判断引用是否有效,如果无效则返回403 Forbidden状态码并停止处理。
保存并关闭配置文件。
测试Nginx配置是否正确:
在命令行中输入sudo nginx -t
,如果显示nginx: configuration file /etc/nginx/nginx.conf test is successful
,则表示配置正确。
重新加载Nginx服务以应用更改:
在命令行中输入sudo systemctl reload nginx
或sudo service nginx reload
。
现在,Nginx已经配置好防盗链功能。当其他网站尝试直接链接到你的资源文件时,将无法访问,从而保护了你的带宽和资源。