Best way to redirect non-CloudFront requests to CloudFront

WheresWardy nginx-forum at
Thu May 3 13:05:48 UTC 2012

A summary of what I want to do is to redirect requests for image URL's
that don't come from Amazon's CloudFront service to CloudFront. This is
because I'm using origin pull, but what the redirect to be done at the
nginx level.

Obviously this won't work:

rewrite ^/(.*).(png|gif|jpg)$1.$2

because CloudFront's original requests will be redirected to itself, and
also because I've got some further rewriting going on for WordPress
image uploads (such that /files/myimage.png will be redirected to a PHP
script for some sites, so I need that redirect to still happen and the
one above to be bypassed in those instances when CloudFront is trying to
do it's original lookup).

What I want to do is basically say:

if ($remote_addr !~ "") {
   rewrite ^/(.*).(png|gif|jpg)$1.$2

but this isn't possible (as remote_addr is an IP that may change) and is
probably inefficient. Is there a correct way to redirect everything to a
hostname that doesn't come from the hostname itself efficiently?

Posted at Nginx Forum:,226015,226015#msg-226015

More information about the nginx mailing list