Serving static content from a subdomain in asp.net using URL Rewrite

天大地大妈咪最大 提交于 2019-12-25 05:57:07

问题


Searched for a few hours with no avail so here goes...

I have a domain which is receiving quite a few hits per day and have been asked if I can serve the static content from a subdomain. As the site is quite extensive and already written, I was wondering if there is any way I can use URL rewriting to change:

www.example.com/image.gif

to

static.example.com/image.gif

I have a solution which works using 301 redirects but from what I understand, this is counter productive as 2 requests will have to be made per image. I don't really want to go through all the aspx pages and css to hard code the new url as it will cause problems further down the line - some parts of the site are still being developed and static content could change at any time. I tried using rewrite (as opposed to redirect) to change the url but it came out something like:

http://www.example.com/http://static.example.com/image.gif

How would you achieve this? I have full access to dns and the server (win 2008r2 / IIS 7.5) so can make any changes if url rewriting is not the answer.

Thanks in advance

Tom.


回答1:


You can accomplish this using an HttpModule. The following example captures all requests for gif files, and changes the absolute path to point to your alternate site that hosts the static content. Try this method inside of a HttpModule:

    private void Application_BeginRequest(Object source, EventArgs e)
    {
        // Create HttpApplication and HttpContext objects to access
        // request and response properties.
        HttpApplication application = (HttpApplication)source;
        HttpContext context = application.Context;
        string filePath = context.Request.FilePath;
        string fullPath = context.Request.Url.AbsoluteUri;
        string fileExtension = VirtualPathUtility.GetExtension(filePath);
        if (fileExtension.Equals(".gif"))
        {
            context.Response.ContentType = "image/gif";
            context.Response.Redirect(fullPath.Replace("www.example.com", "static.example.com"));
        }
    }

For more about HttpModule, go here: http://msdn.microsoft.com/en-us/library/ms227673.aspx

I tested the above code - it works. I hope this helps.



来源:https://stackoverflow.com/questions/5108364/serving-static-content-from-a-subdomain-in-asp-net-using-url-rewrite

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!