目次
1. 经由过程 URL Rewrite Module 组件
2. 经由过程 nginx 图片防盗链
3.自定义 HttpHandler 处置惩罚
4. 经由过程 MVC 自定义路由划定规矩防盗链
5. 经由过程 MVC 自定义 RouteHandler 防盗链
6. 经由过程 HttpModModule 防盗链
7. 触及学问点,相干资本
本身网站上的图片被别的网站盗用是一件很令人厌恶的事变,下面是处置惩罚图片盗链的几种要领。
在这里先交卸一下环境,我用的是 MVC4 ,IIS7 应用顺序池为集成形式,以下设置都是基于此环境举行。
1. 经由过程 URL Rewrite Module 组件
这是一个比较简单,轻易的要领。起首要去 Url Rewite 官网 下载 URL Rewrite Module 2.0 并装置。装置完成后能够看到 IIS设置里多了 URL重写 的模块以下图:
在这里,能够对URL接见划定规矩举行设置, 双击 URL 重写,添到场站划定规矩
在前提(c) 内里增加 {HTTP_REFERER} 形式为: ^http://localhost/.*$, 意义是 要求 HTTP_REFERER 必需包括 http://localhost/ 字符,划定规矩固然是依据本身的状况写。
增加保留后,站点的 web.config 文件的 system.webServer 节点下就多了 rewrite 节点,设置以下。
<system.webServer><validation validateIntegratedModeConfiguration="false" /> <handlers> <remove name="ExtensionlessUrlHandler-Integrated-4.0" /> <remove name="OPTIONSVerbHandler" /> <remove name="TRACEVerbHandler" /> <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" /></handlers><rewrite><rules><rule name="防盗链" stopProcessing="true"><match url=".*\.(gif|jpg|png)" /><conditions> <add input="{HTTP_REFERER}" pattern="^http://localhost/.*$" negate="true" /></conditions><action type="Redirect" url="http://www.baidu.com" /></rule></rules></rewrite> </system.webServer>
设置好了,有无结果呢,我们做一个测试页面尝尝
<!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"/><title></title></head><body><img src="Content/webpage/img/111.jpg" /><img src="111.jpg"/></body></html>
内里有2张图片,因为在IIS “入站划定规矩前提” 内里设置的 HTTP_REFERER 正则表达式为 ^http://localhost/.*$ 假如划定规矩有用,我们接见 http://localhost/HtmlPage1.html 图片应平常显现,而假如经由过程 http://127.0.0.1/HtmlPage1.html 接见是不应该显现图片的,下面是我经由过程这两个地点接见结果。
申明设置是胜利的。固然了,URL Rewrite Module 并不是仅仅做图片防盗链哟!
2. 经由过程 nginx 图片防盗链
防盗链的道理都是一样的,主如果经由过程 referer 推断泉源站点,假如泉源站点不在 “白名单” 里,则谢绝或返回一张默许图片
location ~.*\.(jpg|gif|png)$ { valid_referers none blocked *.abc.com abc.com; if ($invalid_referer) { #rewrite ^/ http://abc.com/error.html; return 403; } }
location ~.*\.(jpg|gif|png)$ 示意一切 以 jpg|gif|png 为后缀名的文件都举行防盗链处置惩罚
valid_referers none blocked *.abc.com abc.com; 考证 referer 个中 none 示意直接接见的,不存在referer blocked为依据防火墙假装的 referer
假如图片是放盗链,重定向到 地点 ,平常是图片地点,然则要注意,这个图片地点不只能在此防盗链划定规矩里,不然也接见不到。 对 nginx 设置不熟悉的同砚请参考 windows 下设置 Nginx 常见题目 要领步骤: 1 建立自定义 handlers 代码以下,依据 Referre 推断要求泉源,假如相符规范,输出文件流,不然住手相应。也能够输出一个特定的图片。
namespace WeiXinDemo.Globals {/// <summary>/// 测试 Handler 完成图片防盗链/// </summary>public class MyImgHandler : IHttpHandler {public bool IsReusable {get { return false; } } public void ProcessRequest(HttpContext context) {var response = context.Response;var request = context.Request; if (request.UrlReferrer == null || !WebApplication.ImgHost.Equals(request.UrlReferrer.Host)) { response.End();return; }var fileName = context.Server.MapPath(request.FilePath); response.WriteFile(fileName);if (request.UrlReferrer == null || WebApplication.ImgHost.Equals(request.UrlReferrer.Host)) { response.WriteFile(fileName); }else{ response.End(); } } } }
2 在web.config 文件 handlers 节点下增加自定义 Handler,满足要求的要求进入 举行处置惩罚
<system.webServer> <handlers> <remove name="ExtensionlessUrlHandler-Integrated-4.0" /> <remove name="OPTIONSVerbHandler" /> <remove name="TRACEVerbHandler" /> <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
<!-- 这是增加的自定义Handler --> <add name="jpgHandler" path="*.jpg" verb="*" type="WeiXinDemo.Globals.MyImgHandler,WeixinDemo" />
<add name="pngHandler" path="*.png" verb="*" type="WeiXinDemo.Globals.MyImgHandler,WeixinDemo" />
<add name="bmpHandler" path="**.bmp" verb="*" type="WeiXinDemo.Globals.MyImgHandler,WeixinDemo" />
<add name="gifHandler" path="*.gif" verb="*" type="WeiXinDemo.Globals.MyImgHandler,WeixinDemo" /></handlers> </system.webServer>
4. 经由过程 MVC 自定义路由划定规矩防盗链
起首我们要在 web.config 文件里 system.webServer 节点下 设置<modules runAllManagedModulesForAllRequests="true" /> 同时还要在 RouteConfig.cs 文件里增加 routes.RouteExistingFiles = true;确保一切路由都经由过程 RouteCollection 婚配 。
在这里我们需要相识 UrlRoutingModule,它是System.Web.Routing的一部分。UrlRoutingModule用于磨练要求的url和当地硬盘 中的文件能不能相婚配。假如婚配,则交给IIS处置惩罚。假如不婚配它会磨练 RouteCollection 来决议能不能继承通报要求。而设置了 runAllManagedModulesForAllRequests="true" 后,会转变默许行动,一切要求都需要 应用 Routing来处置惩罚。
<system.webServer><validation validateIntegratedModeConfiguration="false" /><modules runAllManagedModulesForAllRequests="true" /> <handlers> <remove name="ExtensionlessUrlHandler-Integrated-4.0" /> <remove name="OPTIONSVerbHandler" /> <remove name="TRACEVerbHandler" /> <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" /></handlers> </system.webServer>
设置文件设置好今后增加自定义路由划定规矩,下面是自定义路由划定规矩的完成代码,实在内里就做了一件事,运用正则表达式推断当前要求是不是相符划定规矩,假如相符划定规矩,则进入指定的处置惩罚页面,不然去婚配其他的路由划定规矩。
namespace WeiXinDemo.Globals {/// <summary>/// 图片路由划定规矩(自定义)/// </summary>public class ImgRouteRule : IRouteConstraint { public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection) {var regex = new Regex(@"/[^/]+(.jpg|.bmp|.gif|.png)");var result = regex.IsMatch(httpContext.Request.RawUrl); return result; } } }
如许就造成了一个题目,一切的要求(比方 .css .js .htm 等等)都去路由划定规矩内里去婚配,假如在路由划定规矩内里婚配不到那末就会返回 404,怎样防止呢?经由过程 RouteConfig.cs 文件设置疏忽。
public class RouteConfig {public static void RegisterRoutes(RouteCollection routes) {//确保一切路由都经由过程 RouteCollection 婚配(图片防盗链)routes.RouteExistingFiles = true;//疏忽 json,html,js,css文件routes.IgnoreRoute("{*pathInfo}", new { pathInfo = @".+(.json|.html|.js|.css)" }); routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); //相符路由划定规矩的转到控制器 ImgRule/Index 处置惩罚 (自定义路由划定规矩完成 图片防盗链) routes.MapRoute( name: "ImagesRoute", url: "{*catchall}", defaults: new { controller = "ImgRule", action = "Index" },// ImgRouteRule 为自定义路由划定规矩,相符此划定规矩,进入路由 接见 ImgRule/Index constraints: new { customConstraint = new ImgRouteRule() },//控制器类定名空间namespaces: new[] { "WeiXinDemo.Controllers" }); routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); } }
在上面的代码里设置了 "ImagesRoute" 的路由,运用的自定义路由划定规矩,当满足划定规矩时,跳转到 ImgRule/Index 去处置惩罚,处置惩罚代码跟运用 HttpHandler 相似
public class ImgRuleController : Controller {// GET: ImgRulepublic FileStreamResult Index() {var fPath = Server.MapPath("~" + Request.FilePath);if (Request.UrlReferrer == null) return null; if (!System.IO.File.Exists(fPath) || !WebApplication.ImgHost.Equals(Request.UrlReferrer.Host) || !WebApplication.ImgHost.Equals(Request.UrlReferrer.Host)) return null; return GetFile(fPath); }private FileStreamResult GetFile(string fPath) { return File(new FileStream(fPath, FileMode.Open, FileAccess.Read), GetContentType(Request.FilePath)); }private static string GetContentType(string url) {switch (Path.GetExtension(url)) {case ".gif":return "Image/gif";case ".jpg":return "Image/jpeg";case ".png":return "Image/png";default:break; }return null; } }
5. 经由过程 MVC 自定义 RouteHandler 防盗链
1 文件设置同,也要开启 2 建立自定义路由,自定义路完成代码以下 ,同时另有自定义路由挪用的 ,
using System.IO;using System.Text.RegularExpressions;using System.Web;using System.Web.Routing;namespace WeiXinDemo.Globals {/// <summary>/// 测试自定义 RouteHandler 图片防盗链/// </summary>public class ImageRouteHandler : IRouteHandler {public IHttpHandler GetHttpHandler(RequestContext requestContext) { return new ImageHandler(); } } /// <summary>/// 自定义路由挪用的 HttpHandler/// </summary>public class ImageHandler : IHttpHandler {public ImageHandler() { } public bool IsReusable {get{return true; } } public void ProcessRequest(HttpContext context) {var response = context.Response;var request = context.Request; if (request.UrlReferrer == null || !WebApplication.ImgHost.Equals(request.UrlReferrer.Host)) { response.End();return; }var fileName = context.Server.MapPath(request.FilePath); response.WriteFile(fileName); } } }
RouteConfig.cs 文件设置 以下,这里指定了 对根目次下的 jpg 文件的接见进入指定路由处置惩罚顺序 ImageRouteHandler。 实在这里能够把图片都放在某一个特定文件夹下,然后对这个文件夹下文件的接见做放盗链。
namespace WeiXinDemo {public class RouteConfig {public static void RegisterRoutes(RouteCollection routes) {//确保一切路由都经由过程 RouteCollection 婚配(图片防盗链)routes.RouteExistingFiles = true;//疏忽 json,html,js,css文件routes.IgnoreRoute("{*pathInfo}", new { pathInfo = @".+(.json|.html|.js|.css)" }); routes.IgnoreRoute("{resource}.axd/{*pathInfo}");//图片防盗链routes.Add("ImagesRoute",new Route("{name}.jpg", new ImageRouteHandler())); routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); } } }
6. 经由过程 HttpModule 防盗链
1. 修正 web.config 设置文件
<system.webServer><modules runAllManagedModulesForAllRequests="true" > <add name="ImgModule" type="WeiXinDemo.Globals.ImageModel,WeiXinDemo"/></modules> <handlers> <remove name="ExtensionlessUrlHandler-Integrated-4.0" /> <remove name="OPTIONSVerbHandler" /> <remove name="TRACEVerbHandler" /> </handlers> </system.webServer>
2. 建立完成 IHttpModule 接口的 ImageModel 类
+= BeginRequest(= regex = Regex( request = (!regex.IsMatch(request.RawUrl)) (request.UrlReferrer == || ! fileName =
3. RouteConfig.cs 文件疏忽不需要防盗链的静态资本
using System.Web.Mvc;using System.Web.Routing;namespace WeiXinDemo {public class RouteConfig {public static void RegisterRoutes(RouteCollection routes) {//确保一切路由都经由过程 RouteCollection 婚配(图片防盗链)routes.RouteExistingFiles = true;//疏忽 json,html,js,css文件routes.IgnoreRoute("{*pathInfo}", new { pathInfo = @".+(.json|.html|.js|.css)" }); routes.IgnoreRoute("{resource}.axd/{*pathInfo}");routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); } } }
7. 触及学问
本文只做了一件事变,图片防盗链,实在从差别的完成体式格局来看它触及到差别的学问。
1. URL Rewrite Module 组件的运用
怎样运用mod_rewrite模块完成URL重写
Creating Rewrite Rules for the URL Rewrite Module
2. Nginx
借助Nginx搭建反向代理服务器
运用nginx实行负载平衡
3. IIS 事情道理,asp.net 管线
IIS是怎样处置惩罚ASP.NET要求的
ASP.NET那点不为人知的事
IIS 内部运行机制
ASP.NET MVC5要求管道和生命周期
ASP.NET MVC要求处置惩罚管道生命周期的19个关键环节(1-6)
4. Mvc UrlRouting 处置惩罚机制
MVC之前的那点事儿系列(8):UrlRouting的明白
本文只是在这里探讨了一下完成防盗链的要领,没有斟酌机能的题目,假如斟酌机能跟简便性,我个人喜好用 第 1 和第 2种完成体式格局,第 3种 次之。 条条大路通罗马,就看那种要领最适合。
以上就是asp.net MVC 网站图片怎样完成防盗链?的细致内容,更多请关注ki4网别的相干文章!