Search code examples
url-rewritingcdn

How to replace certain images urls point to CDN server?


My cdn server has copies of image files for my site. Let' says my images are in http://example.com/images.

Is it possible to replace all the url of http://example.com/images/*.* to http://mycdn.com/images/*.* ? So that user loads the images from my CDN server.

The site runs in LAMP.


Solution

  • I think you mean mod_rewrite?

    You cannot do an internal path rewrite to send a request to a different server; you will need to send a redirect:

    RewriteRule ^/images/(.*)$  http://mycdn.com/images/$1 [R]
    

    That will work. However, it defeats some of the advantage of using the CDN by slowing things down quite a bit: a client first has to request the image from your server, then has to follow the redirect to the CDN.

    The better thing is to simple make all your CSS files and img tags point directly to the CDN. The rewrite is really only acceptable as a stopgap or transitional measure.