Skip to main content
2 of 4
Updated URL to CDN (used the wrong one from the question)
MrWhite
  • 43.1k
  • 4
  • 50
  • 90
  1. I initially tried mod_rewrite in my .htaccess ...

You could perhaps use mod_rewrite together with mod_proxy to create a reverse proxy to your CDN. This has the advantage of hiding the location of your CDN. For example, in your HTML, reference your assets in a "virtual" subdirectory, eg. /cdn.

src="/cdn/WebsiteData/images/img1.jpg"

Then use mod_rewrite/mod_proxy to proxy all requests for /cdn/.... to your CDN (S3):

RewriteRule ^cdn/(.*) https://s3.<location>.amazonaws.com/elasticbeanstalk-<location>-<id>/$1 [P]

That is, assuming your server has the necessary modules loaded (mod_proxy, mod_proxy_http) and S3 permits proxied requests.

  1. Next, I tried a PHP solution: <img src="<?php echo $aws_s3_folder; ?>/WebsiteData/images/img1.jpg" alt="My image"/>. This works, obviously.

This doesn't feel like an "ugly hack" to me. (Unless maybe this is the only thing you are using PHP for?) In fact, this would probably be my preferred solution I think. I would, however, use the short echo format: <?=$aws_s3_folder?>

  1. I wrote a small Javascript script which just changes all links...

However, the JavaScript solution does feel like a hack. And could certainly result in some client-side errors (404s) before the code runs.

###BASE Element

Another solution might be to use relative paths to all your S3 assets and include the base element in the head section of your HTML to tell the browser where these assets are. For example:

src="WebsiteData/images/img1.jpg"

Then, in your base tag (NB: Include the trailing slash on this path):

<base href="<?=$aws_s3_folder?>/">
MrWhite
  • 43.1k
  • 4
  • 50
  • 90