在 CentOS 上,如果使用 Apache(httpd) 做 Web 服务器,防盗链(防止其他网站盗用你的图片、视频、文件等)通常通过 Apache 的 mod_rewrite 模块来实现。
下面给你几种常用、实用的做法。
CentOS 一般使用 httpd:
httpd -M | grep rewrite
如果没有看到 rewrite_module,启用它:
vim /etc/httpd/conf.modules.d/00-base.conf
确保有这一行(通常默认有):
LoadModule rewrite_module modules/mod_rewrite.so
然后重启 Apache:
systemctl restart httpd
编辑你的站点配置(如 /etc/httpd/conf.d/your-site.conf):
<VirtualHost *:80>
ServerName www.example.com
DocumentRoot /var/www/html
<Directory "/var/www/html">
Options -Indexes +FollowSymLinks
AllowOverride All
Require all granted
</Directory>
# 防盗链
RewriteEngine On
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http://(www\.)?example\.com [NC]
RewriteCond %{HTTP_REFERER} !^https://(www\.)?example\.com [NC]
RewriteRule \.(jpg|jpeg|png|gif|webp|mp4|zip)$ - [F]
</VirtualHost>
✅ 效果:
example.com 引用图片/视频.htaccess 防盗链(更灵活)如果你的目录支持 .htaccess(AllowOverride All),可以直接在网站根目录创建:
vim /var/www/html/.htaccess
内容:
RewriteEngine On
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^https?://(www\.)?example\.com [NC]
RewriteRule \.(jpg|jpeg|png|gif|webp|mp4|zip)$ - [F]
✅ 优点:
你也可以把盗链请求重定向到一张“警告图”:
RewriteEngine On
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^https?://(www\.)?example\.com [NC]
RewriteRule \.(jpg|png|gif)$ http://www.example.com/static/steal.png [R,L]
RewriteRule \.(jpg|jpeg|png|gif|webp)$ - [F]
RewriteCond %{HTTP_REFERER} !^$
从别的网站引用你的图片:
<img src="http://www.example.com/a.jpg">
应返回 403
如果你愿意,我可以:
你用的是 Apache 2.4 吗?网站是图片站还是视频站?