How To Fix: 404 Error When Requesting Images Hosted on IIS Under a Frontend Website

Hosting images on an IIS server seems to be pretty much a basic task. 

I mean all you need is to create a virtual directory or even a website and just move the pictures to the physical path of this website and then you can access it through:

server-hostname.com/virtual-directory/picture-name.jpg

Well while this might be something that you can apply easily, following the same steps but instead of creating a new website you go for adding a virtual directory under an existing frontend website might yield the world famous 404 error.

The Problem

I was working on a project once where I needed to create an API that takes an image url as a parameter and downloads it on the same server where the UI of the application was hosted. 

I will show you how to create such an API in an upcoming post but right now let's focus on creating a virtual path under your frontend website.


After you open your IIS manager right click your frontend website click on Add Virtual Directory and select the physical path (eg. C:/example/server-images) where you want to store your images and then provide a virtual path (eg. images) that maps to this image directory.

Add any image to the physical directory and you should be able to access it through the url format I mentioned at the beginning of the article but you might face a 404 error. So now what?

The Cause

It turns out that the web.config of the frontend website had a rewrite rule.

    <rewrite>

      <rules>

        <rule name="myapp">

          <match url="/*" />

          <action type="Rewrite" url="server.js" />

        </rule>

      </rules>

    </rewrite>

This means that any incoming request will be redirected to server.js because of the wildcard matching (/*) including my call to my virtual path (/images). Then how do we fix this?

The Solution

Simply add a condition that exempts your virtual path from the url rewrite rule in order to allow you requests to reach your virtual path such as follows but just make sure to replace (/images/) with the name of your virtual path.

<rewrite>

  <rules>

    <rule name="myapp">

      <match url="/*" />

      <conditions>

        <add input="{REQUEST_URI}" pattern="^/images/" negate="true" />

      </conditions>

      <action type="Rewrite" url="server.js" />

    </rule>

  </rules>

</rewrite>

By doing so you will finally be able to reach your images on your virtual path.


Perfect! Now your problem should be solved. See you in later posts!

Comments

Popular posts

Why I Hate Microservices Part 1: The Russian Dolls Problem 🪆🪆🪆

Why I Hate Microservices Part 3: The Identity Crisis 😵

Why I Hate Microservices Part 2: The Who's Telling the Truth Problem 🤷