Apache 防盗链的第一种实现方法,可以用 rewrite 实现.首先要确认 Apache 的 rewrite module 可用.能够控制 Apachehttpd.conf 文件的,打开 httpd.conf,确保有这么一行配置:

LoadModule rewrite_module modules/mod_rewrite.so

然后在找到自己网站对应的配置的地方,加入下列代码:

ServerName shuxun.wang
# 防盗链配置
RewriteEngine On
RewriteCond %{HTTP_REFERER} !^http://shuxun.wang/.*$ [NC]
RewriteCond %{HTTP_REFERER} !^http://shuxun.wang$ [NC]
RewriteCond %{HTTP_REFERER} !^http://www.shuxun.wang/.*$ [NC]
RewriteCond %{HTTP_REFERER} !^http://www.shuxun.wang$ [NC]
RewriteRule .*.(gif|jpg|swf)$ http://www.shuxun.wang/about/nolink.png [R,NC]

然后重新启动 apache 服务器即可. 有些用户使用的是虚拟主机,没有服务器的控制权,无法修改 httpd.conf 文件和重启服务器.那么请确认你的虚拟主机支持.htaccess,将上面的配置写入 .htaccess 文件,放入根目录或图片所在的目录即可: .htaccess 文件的内容:

# 防盗链配置
RewriteEngine On
RewriteCond %{HTTP_REFERER} !^http://shuxun.wang/.*$ [NC]
RewriteCond %{HTTP_REFERER} !^http://shuxun.wang$ [NC]
RewriteCond %{HTTP_REFERER} !^http://www.shuxun.wang/.*$ [NC]
RewriteCond %{HTTP_REFERER} !^http://www.shuxun.wang$ [NC]
RewriteRule .*.(gif|jpg|swf)$ http://www.shuxun.wang/about/nolink.png [R,NC]

注意: httpd.conf 文件里的配置,是在 apache 启动时一次读取,效率很高. .htaccess 文件里的配置,每次访问都需要读取分析,效率很低. 使用 SetEnvIfNoCase 和 access 技术实现 Apache 防盗链 另一种方式是利用 SetEnvIfNoCase 和 access.具体的代码如下:

SetEnvIfNoCase Referer "^http://shuxun.wang" local_ref=1
SetEnvIfNoCase Referer "^http://www.shuxun.wang" local_ref=1
Order Allow,Deny
Allow from env=local_ref

将上述代码,放入前面所讲的 httpd.conf 或 .htaccess 文件即可.