AI OnAI Off
If you want to do it yourself you'll need to look at overriding the friendly URL mechanism. It would be worth baring in mind that, if you're caching indefinitely, updates to existing images won't show up so you may also want to adjust the URL to inject a timestamp or other version-specific identifier.
The easier option is to use the CDN support module which was built for precisely this situation. You can find it here:
https://github.com/bjuris/EPiServer.CdnSupport/
Even if you don't use it directly, the code in there should give you a good start on what you're trying to do.
Thanks to you both. I ended up using a variant of Dejans answer. However he seems to have removed his answer for some reason.
We are using an NGINX-machine to serve our images on s.domain.com. It is setup to cache images forever and when it doesn't have an image it asks one of our webbservers for it and then caches it forever.
We simply append s.domain.com to any image URLs that come from our code and everything works fine. So we get http://s.domain.com/globalassets/image.png
However, when users upload images in a TínyMCE-editor for an XHtmlString they are outputted as /globalassets/image.png and I can't figure out a good way to adjust these URLs to that they use the NGINX-machine. Is there any way to tell Episerver how to render an image added in a TinyMCE-editor?