IIS7.0下防盗链设置, .
分类: Asp.net 2011-07-11 16:27 4人阅读 评论(0) 收藏 编辑 删除
常见的asp.net防盗链的方法是写一个HttpHandler类,实现IHttpHandler接口,代码如下:
public class ImageHandler : IHttpHandler {
public void ProcessRequest (HttpContext context) {
//判断是否是本地网站引用图片,如果是则返回正确的图片
if (context.Request.UrlReferrer!=null && context.Request.UrlReferrer.Host.Equals("localhost"))
{
//设置客户端缓冲时间过期时间为0,即立即过期
context.Response.Expires =0;
//清空服务器端为此会话开启的输出缓存
context.Response.Clear();
//设置输出文件类型
context.Response.ContentType = "image/jpg";
//将请求文件写入到输出缓存中
context.Response.WriteFile(context.Request.PhysicalPath);
//将输出缓存中的信息传送到客户端
context.Response.End();
}
//如果不是本地引用,则是盗链本站图片
else
{
//设置客户端缓冲时间过期时间为0,即立即过期
context.Response.Expires = 0;
//清空服务器端为此会话开启的输出缓存
context.Response.Clear();
//设置输出文件类型
context.Response.ContentType = "image/jpg";
//将请求文件写入到输出缓存中
context.Response.WriteFile(context.Request.PhysicalApplicationPath + "imgs/fdl.jpg");
//将输出缓存中的信息传送到客户端
context.Response.End();
}
}
public bool IsReusable {
get {
return false;
}
}
完事后再在web.config中加入如下配置,
<httpHandlers>
<add verb="*" type="ImageHandler" path="*.jpg,*.jpeg" validate="false"/>
</httpHandlers>
在本地运行可以通过,但貌似在iis7.0下防盗链通不过,当然在本地运行也是一个问题(环境:asp.net4.0),iis7.0下访盗链可以通过如下方法实现:
前提:需要安装:ISAPI_Rewrite3
下载地址:http://www.helicontech.com/download.htm
<system.webServer>
<rewrite>
<rules>
<rule name="Forbid image">
<match url="\.(txt|doc|gif|jpg|jpeg|png|mp3|flv|swf)$" ignoreCase="false" />
<conditions>
<add input="{HTTP_REFERER}" pattern="^$" ignoreCase="false" negate="true" />
<add input="{HTTP_REFERER}" pattern="^http://(www\.)?passji.com/.*$" negate="true" />
</conditions>
<action type="CustomResponse" statusCode="403" statusReason="Forbidden" statusDescription="Forbidden" />
</rule>
</rules>
</rewrite>
</system.webServer>
如果你想让盗链你的图片的网站上显示你准备的"禁止盗链“之类的图片,请将
<action type="CustomResponse" statusCode="403" statusReason="Forbidden" statusDescription="Forbidden" />
修改成:
<action type="Rewrite" url="/imgs/fbl.png" />
imgs/fbl.png根据你实际的图片位置和名称做修改。通过测试,iis7.0下防盗链可以通过。
还有一种方法:就是写一个.htaccess为后缀的配置文件!然后在iis上导入配置规则!
RewriteCond %{HTTP_REFERER} !^$ [NC]
RewriteCond %{HTTP_REFERER} !google.com [NC]
RewriteCond %{HTTP_REFERER} !baidu.com [NC]
RewriteCond %{HTTP_REFERER} !soso.com [NC]
RewriteCond %{HTTP_REFERER} !bing.com [NC]
RewriteRule .*\.(gif|jpg|jpeg|bmp|png)$ http://www.wovane.com/fbl.png [R,NC,L]
参考:http://wenku.baidu.com/view/6121f509581b6bd97f19eace.html