A caching, resizing image proxy written in Go
https://github.com/willnorris/imageproxy.git
imageproxy is a caching image proxy server written in go. It features:
I aim to keep imageproxy compatible with the two most recent major go releases. I also keep track of the minimum go version that still works (currently go1.18), but that might change at any time. You can see the go versions that are tested against in .github/workflows/tests.yml.
imageproxy URLs are of the form http://localhost/{options}/{remote_url}.
Options are available for cropping, resizing, rotation, flipping, and digital signatures among a few others. Options for are specified as a comma delimited list of parameters, which can be supplied in any order. Duplicate parameters overwrite previous values.
See the full list of available options at
The URL of the original image to load is specified as the remainder of the path. It may be included in plain text without any encoding, percent-encoded (aka URL encoded), or base64 encoded (URL safe, no padding).
When no encoding is used, any URL query string is treated as part of the remote URL.
For example, given the proxy URL of http://localhost/x/http://example.com/?id=1,
the remote URL is http://example.com/?id=1.
When percent-encoding is used, the full URL must be encoded.
Any query string on the proxy URL is NOT included as part of the remote URL.
Percent-encoded URLs must be absolute URLs;
they cannot be relative URLs used with a default base URL.
For example, http://localhost/x/http%3A%2F%2Fexample.com%2F%3Fid%3D1.
When base64 encoding is used, the full URL must be encoded.
Any query string on the proxy URL is NOT included as part of the remote URL.
Base64 encoded URLs may be relative URLs used with a default base URL.
For example, http://localhost/x/aHR0cDovL2V4YW1wbGUuY29tLz9pZD0x.
The following live examples demonstrate setting different options on this source image, which measures 1024 by 678 pixels.
smart crop feature can best be seen by comparing crops of this source image, with and without smart crop enabled.| Options | Meaning | Image |
|---|---|---|
| 150x300 | 150x300px, standard crop | ![]() |
| 150x300,sc | 150x300px, smart crop | ![]() |
Transformation also works on animated gifs. Here is this source image resized to 200px square and rotated 270 degrees:
Install the package using:
go install willnorris.com/go/imageproxy/cmd/imageproxy@latest
Once installed, ensure $GOPATH/bin is in your $PATH, then run the proxy
using:
imageproxy
This will start the proxy on port 8080, without any caching and with no allowed
host list (meaning any remote URL can be proxied). Test this by navigating to
By default, the imageproxy command does not cache responses, but caching can be
enabled using the -cache flag. It supports the following values:
memory - uses an in-memory LRU cache. By default, this is limited tomemory:size:age where size is measured in mb and age is a
duration. For example, memory:200:4h will create a 200mb cache that will
cache items no longer than 4 hours.
/tmp/imageproxy) - will cache imagess3://region/bucket-name/optional-path-prefix) - will cacheAWS_ACCESS_KEY_ID and AWS_SECRET_KEY
environmental variables be set. (Additional methods of loading credentials
are documented in the aws-sdk-go session
package).
Additional configuration options ([further documented here]) may be specified as URL query string parameters, which are mostly useful when working with s3-compatible services:
s3://fake-region/bucket/folder?endpoint=minio:9000&disableSSL=1&s3ForcePathStyle=1
Similarly, for Digital Ocean Spaces, provide a dummy region value and the appropriate endpoint for your space:
s3://fake-region/bucket/folder?endpoint=sfo2.digitaloceanspaces.com
[aws-options]: https://docs.aws.amazon.com/sdk-for-go/api/aws/#Config
gcs://bucket-name/optional-path-prefix) - will cache imagesazure://container-name/) - will cache images onAZURESTORAGE_ACCOUNT_NAME and
AZURESTORAGE_ACCESS_KEY environment variables to bet set.
redis://hostname/) - will cache images onREDIS_PASSWORD
environment variable.
For example, to cache files on disk in the /tmp/imageproxy directory:
imageproxy -cache /tmp/imageproxy
Reload the codercat URL, and then inspect the contents of
/tmp/imageproxy. Within the subdirectories, there should be two files, one
for the original full-size codercat image, and one for the resized 500px
version.
Multiple caches can be specified by separating them by spaces or by repeating
the -cache flag multiple times. The caches will be created in a [tiered
fashion]. Typically this is used to put a smaller and faster in-memory cache
in front of a larger but slower on-disk cache. For example, the following will
first check an in-memory cache for an image, followed by a gcs bucket:
imageproxy -cache memory -cache gcs://my-bucket/
By default, imageproxy will respect the caching directives in response headers,
including the cache duration and explicit instructions not to cache the response,
such as no-store and private cache-control directives.
You can force imageproxy to cache responses, even if they explicitly say not to,
by passing the -forceCache flag. Note that this is generally not recommended.
A minimum cache duration can be set using the -minCacheDuration flag. This
will extend the cache duration if the response header indicates a shorter value.
If called without the -forceCache flag, this will have no effect on responses
with the no-store or private directives.
imageproxy -cache /tmp/imageproxy -minCacheDuration 5m
You can limit images to only be accessible for certain hosts in the HTTP referrer header, which can help prevent others from hotlinking to images. It can be enabled by running:
imageproxy -referrers example.com
Reload the codercat URL, and you should now get an error message. You can
specify multiple hosts as a comma separated list, or prefix a host value with
*. to allow all sub-domains as well.
You can limit the remote hosts that the proxy will fetch images from using the
allowHosts and denyHosts flags. This is useful, for example, for locking
the proxy down to your own hosts to prevent others from abusing it. Of course
if you want to support fetching from any host, leave off these flags.
Try it out by running:
imageproxy -allowHosts example.com
Reload the codercat URL, and you should now get an error message. Alternately, try running:
imageproxy -denyHosts octodex.github.com
Reloading the codercat URL will still return an error message.
You can specify multiple hosts as a comma separated list to either flag, or
prefix a host value with *. to allow or deny all sub-domains. You can
also specify a netblock in CIDR notation (127.0.0.0/8) -- this is useful for
blocking reserved ranges like 127.0.0.0/8, 192.168.0.0/16, etc.
If a host matches both an allowed and denied host, the request will be denied.
You can limit what content types can be proxied by using the contentTypes
flag. By default, this is set to image/*, meaning that imageproxy will
process any image types. You can specify multiple content types as a comma
separated list, and suffix values with * to perform a wildcard match. Set the
flag to an empty string to proxy all requests, regardless of content type.
Instead of an allowed host list, you can require that requests be signed. This is useful in preventing abuse when you don't have just a static list of hosts you want to allow. Signatures are generated using HMAC-SHA256 against the remote URL, and url-safe base64 encoding the result:
base64urlencode(hmac.New(sha256, <key>).digest(<remote_url>))
The HMAC key is specified using the signatureKey flag. If this flag
begins with an "@", the remainder of the value is interpreted as a file on disk
which contains the HMAC key.
Try it out by running:
imageproxy -signatureKey "secretkey"
Reload the codercat URL, and you should see an error message. Now load a signed codercat URL (which contains the signature option) and verify that it loads properly.
Some simple code samples for generating signatures in various languages can be
found in docs/url-signing.md. Multiple valid signature
keys may be provided to support key rotation by repeating the signatureKey
flag multiple times, or by providing a space-separated list of keys. To use a
key with a literal space character, load the key from a file using the "@"
prefix documented above.
If both a whiltelist and signatureKey are specified, requests can match either. In other words, requests that match one of the allowed hosts don't necessarily need to be signed, though they can be.
To limit how long a URL is valid (particularly useful for signed URLs),
you can specify a "valid until" time using the vu option with a Unix timestamp.
For example, the following signed URL would only be valid until 2020-01-01:
http://localhost:8080/vu1577836800,sjNcVf6LxzKEvR6Owgg3zhEMN7xbWxlpf-eyYbRfFK4A=/https://example.com/image
Typically, remote images to be proxied are specified as absolute URLs. However, if you commonly proxy images from a single source, you can provide a base URL and then specify remote images relative to that base. Try it out by running:
imageproxy -baseURL https://octodex.github.com/
Then load the codercat image, specified as a URL relative to that base:
By default, the imageproxy won't scale images beyond their original size.
However, you can use the scaleUp command-line flag to allow this to happen:
imageproxy -scaleUp true
Imageproxy can proxy remote webp images, but they will be served in either jpeg or png format (this is because the golang webp library only supports webp decoding) if any transformation is requested. If no format is specified, imageproxy will use jpeg by default. If no transformation is requested (for example, if you are just using imageproxy as an SSL proxy) then the original webp image will be served as-is without any format conversion.
Because so few browsers support tiff images, they will be converted to jpeg by default if any transformation is requested. To force encoding as tiff, pass the "tiff" option. Like webp, tiff images will be served as-is without any format conversion if no transformation is requested.
Run imageproxy -help for a complete list of flags the command accepts. If
you want to use a different caching implementation, it's probably easiest to
just make a copy of cmd/imageproxy/main.go and customize it to fit your
needs... it's a very simple command.
All configuration flags have equivalent environment variables of the form
IMAGEPROXY_$NAME. For example, an on-disk cache could be configured by calling
IMAGEPROXY_CACHE="/tmp/imageproxy" imageproxy
In most cases, you can follow the normal procedure for building a deploying any go application. For example:
go build willnorris.com/go/imageproxy/cmd/imageproxy/usr/local/binetc/imageproxy.service to/lib/systemd/system and enable using systemctl.
Instructions have been contributed below for running on other platforms, but I don't have much experience with them personally.
It's easy to vendorize the dependencies with Godep and deploy to Heroku. Take
a look at this GitHub repo
(make sure you use the heroku branch).
OβReilly Media set up a repository with everything you need to deploy imageproxy to Elastic Beanstalk. Just follow the instructions in the README.
A docker image is available at ghcr.io/willnorris/imageproxy.
You can run it by
docker run -p 8080:8080 ghcr.io/willnorris/imageproxy -addr 0.0.0.0:8080
Or in your Dockerfile:
ENTRYPOINT ["/app/imageproxy", "-addr 0.0.0.0:8080"]
If running imageproxy inside docker with a bind-mounted on-disk cache, make sure the container is running as a user that has write permission to the mounted host directory. See more details in #198.
Note that all configuration options can be set using environment variables, which is often the preferred approach for containers.
You can proxy requests to imageproxy in your Caddy config using the reverse_proxy directive:
@imageproxy path /api/imageproxy/*
handle @imageproxy {
uri replace /api/imageproxy/ /
reverse_proxy http://localhost:4593
}
You can also run an instance of imageproxy embedded in Caddy using the caddy module.
This requires a custom build of Caddy with the imageproxy module included
(example),
and configuring it with the imageproxy directive in your Caddyfile:
@imageproxy path /api/imageproxy/*
handle @imageproxy {
uri replace /api/imageproxy/ /
imageproxy {
cache /data/imageproxy-cache
default_base_url {$IMAGEPROXY_BASEURL}
allow_hosts {$IMAGEPROXY_ALLOWHOSTS}
signature_key {$IMAGEPROXY_SIGNATUREKEY}
}
}
Use the proxy_pass directive to send requests to your imageproxy instance.
For example, to run imageproxy at the path "/api/imageproxy/", set:
location /api/imageproxy/ {
proxy_pass http://localhost:4593/;
}
Depending on other directives you may have in your nginx config, you might need to alter the precedence order by setting:
location ^~ /api/imageproxy/ {
proxy_pass http://localhost:4593/;
}
{{<img>}} shortcode
like this example)
imageproxy is copyright its respective authors. All of my personal work on imageproxy through 2020 (which accounts for the majority of the code) is copyright Google, my employer at the time. It is available under the Apache 2.0 License.