Is it OK to HTTP redirect images?

Is it OK to return a 301 / 302 / 303 code when returning an image resource? I have done this in the past and it seems to work. Is it good practice and is it compatible with most browsers?


Yes, you can redirect images and browsers will follow redirects. But you'll generally want to keep redirection to a minimum for performance reasons, because each redirect requires a separate HTTP request, which adds server overhead and increases end-user page load time a little.

The one thing you should definitely avoid is redirecting many images on a page. This will severely slow down page load time, especially on high-latency networks (e.g. phone, China, satellite internet) where each new HTTP request takes a long time. Also, HTTP clients are limited to a small number of simultaneous HTTP connections per server hostname, so even on fast networks you'll end up with a bottleneck.

Redirecting 1 or 2 images on a page is not a big deal, however.

If you redirect images and they're cacheable, you'd ideally set an HTTP Expires header (and the appropriate Cache-Control header) for a date in the distant future, so at least on subsequent visits to the page users won't have to go through the redirect again.

If the reason you're redirecting is to conform to a new URL scheme, most web servers have an easy way to rewrite URLs on the server without having to send an actual redirect back to the client. In other words, the client may request /static/bar.jpg but the server can be configured to translate that into /media/images/bar.jpg. This URL-rewriting approach is preferable to redirection in most cases, since you can refactor where your content lives on the server without incurring the redirection overhead on the client or server side.


Yes, it works.

About being good practice, what are the alternatives? Returning an error response (404)? Not very helpful. Returning the image that the redirected resource would return? Probably not possible, otherwise you would not redirect. Fixing the img tags with the new URL? Sure, where possible, but maybe you want the browser to go thorough the redirection (a counter maybe).


It's OK if the code actually reflects reality - for example, if an image has indeed moved permanenetly, you should use a 301.