Best way to redirect non-CloudFront requests to CloudFront

Jonathan Matthews contact at
Tue May 8 11:36:47 UTC 2012

On 8 May 2012 10:53, WheresWardy <nginx-forum at> wrote:
> OK, in the end I went with:
> if ($http_user_agent !~ "Amazon CloudFront") {
>    rewrite ^/(.*).(png|gif|jpg)$1.$2
> }
> which seems to do the trick. Seems like there should be a better way of
> doing what must be quite a common form of rewrite though? (Or is this
> the fast alternative to Apache's REWRITE_COND?)

This is an example of the more general "has my request been /from/ the
CDN I'm using, or has it bypassed it?" problem.

The solution is never to leak the un-CDN'd URIs, and enforce that only
the CDN can access them (perhaps via basic auth; perhaps via UA
blocking; perhaps via IP restrictions).

If you've already missed that opportunity, and also don't have a
dedicated static-assets domain you can CNAME to the CDN, then you
could look at using their published list of cloudfront IPs along with and do something like

location ~ \.(png|gif|jpg)$ {
  if ($request_not_from_cloudfront_netblocks) {
    rewrite ^/(.*)$$1;

Yes, it's not *massively* different from what you've got, but I'd
personally prefer it as it doesn't involve a string-based regex only
invokes the geo/map evaluation for those image suffixes, and isn't
externally gameable. Unless "cloudfront netblocks" == "EC2 netblocks",
of course, in which case Amazon have been daft.

Yes, it also requires keeping this geo map IP list up to date. Still
preferable to my mind.

Jonathan Matthews
Oxford, London, UK

More information about the nginx mailing list