5

ASP.NET Core 2.1.

My favicon is at /images/favicon.ico and cannot be changed. So pages include this:

<link href="/images/favicon.ico" rel="shortcut icon" type="image/x-icon" />

And that works.

But requests directly to example.com/favicon.ico will fail with a 404.

How do I redirect example.com/favicon.ico to example.com/images/favicon.ico?

lonix
  • 14,255
  • 23
  • 85
  • 176
  • 1
    Browsers often check for the favicon at the root, regardless of whether it's defined as located somewhere else in the HTML document. They'll eventually load it from the right place, of course, but you still get that first initial request. Adding a redirect won't really do anything for you other than mask the 404, and ultimately it doesn't matter anyways. It's not your job to prevent every possible 404, because you honestly cannot. Any client can *request* anything they want to request; returning a 404 is perfectly acceptable in many cases. – Chris Pratt Aug 10 '18 at 12:45
  • While I answered the question with a working solution, @ChrisPratt's comment made me wonder why you would need `example.com/favicon.ico` to be redirected to the real favicon's location ? If you added the `link` tag indicating the proper location for the favicon you've done all you need to help the browser find it. Why do you want to have this redirection done ? – Mathieu VIALES Aug 10 '18 at 12:50
  • Because not all requests are to html pages. Also I'm not the only one with this [use case](https://stackoverflow.com/a/21359390/9971404). – lonix Aug 10 '18 at 13:04
  • Even google does this. Their favicon can be requested at `/` but is actually located at `https://www.google.com/images/branding/product/ico/googleg_lodp.ico` – lonix Aug 10 '18 at 13:07

1 Answers1

4

In the Configure method of your Startup class, add the following code

RewriteOptions rewriteOptions = new RewriteOptions().AddRedirect("favicon.ico", "images/favicon.ico");

app.UseRewriter(rewriteOptions);

See this page for more information

Mathieu VIALES
  • 4,526
  • 3
  • 31
  • 48
  • I assume the "correct" place to put this is after `app.UseStaticFiles();`? – lonix Aug 10 '18 at 13:09
  • I put it at the very end of the function, right after my `.AddMvc` declaration. I don't really know what the "proper" place is, so as long as it work you're good ;-) – Mathieu VIALES Aug 10 '18 at 13:44
  • Thanks! Do you mind looking at my [related question](https://stackoverflow.com/questions/51787969/url-rewriting-in-asp-net-core-2-1-without-regex)? – lonix Aug 10 '18 at 13:48
  • I was wondering about that... to avoid that part of the pipeline it might be better to place it before `UseMvc()`, and yet that might mean that all requests will go through that check. Not sure... So I've done it your way! :) – lonix Aug 10 '18 at 13:52