使用 rewrite 技术实现 Apache 防盗链

来源:互联网 发布:杭州哪里招淘宝模特 编辑:程序博客网 时间:2024/05/03 20:07

本文参考自以下文章:

http://my.oschina.net/baobao/blog/17524

本地有两个虚拟目录:localhost/t/和localhost/js/,设置Apache使localhost/js/目录中的文件不能引用localhost/t/目录下的图片文件。

1.使Apache的rewrite module可用。打开httpd.conf文件,将#LoadModule rewrite_module modules/mod_rewrite.so前的#去掉。

允许在任何目录中使用“.htaccess”文件,将“AllowOverride”改成“All”(默认为“None”)


# AllowOverride controls what directives may be placed in .htaccess files.    # It can be "All", "None", or any combination of the keywords:    #   Options FileInfo AuthConfig Limit    #    AllowOverride None
修改为:

# AllowOverride controls what directives may be placed in .htaccess files.    # It can be "All", "None", or any combination of the keywords:    #   Options FileInfo AuthConfig Limit    #    AllowOverride All

2.将以下配置写入.htaccess文件,放入根目录或者图片所在的目录即可。

# 防盗链配置 RewriteEngine OnRewriteCond %{HTTP_REFERER} !^$ [NC]RewriteCond %{HTTP_REFERER} !http://localhost/t/ [NC]RewriteRule .*\.(gif|jpg|png)$ http://localhost/t/error.png [R,NC]

重新启动Apache服务器即可。

关于源代码的解释:

1.RewriteCond %{HTTP_REFERER} !^$ [NC]

允许空“HTTP_REFERER”的访问,即允许用户在浏览器地址栏中直接输入图片地址时图片文件的显示。一般而言,这是可选的,不过,建议这么设置,如果强迫必须具有

“HTTP_REFERER”才能访问,可能会带来某些问题,比如说在用户通过代理服务器访问时。

2.RewriteCond %{HTTP_REFERER} !http://localhost/t/ [NC]

设置允许访问的HTTP来源。

3.RewriteRule .*\.(gif|jpg|png)$ http://localhost/t/error.png [R,NC]

定义被盗链时替代的图片,让所有盗链 jpg、gif、png 等文件的网页,显示根目录下的error.png 文件。注意:替换显示的图片不要放在设置防盗链的目录中,并且该图片文件体

积越小越好。另外本人在使用中还发现一个问题,即替换图片为jpg文件时显示出现问题,而使用png文件时则程序正常运行。

4.说明一下其中的R、NC 和 L

R 就是转向的意思
NC 指的是不区分大小写
L 的作用是指明本次转向到此结束,后续的转向不受先前判断语句的影响



原创粉丝点击