NGINX to filter out non matches to url pattern
New here? Learn about Bountify and follow @bountify to get notified of new bounties! x

I am using an image proxy which is behind nginx and i want to make sure the world doesn't use my image proxy for their own images.

the proxy is generally expecting a url like this

In the above case i would want to whitelist "" or rather "*" so that we can ensure that proxy requests asking for other domains aren't ours. Ideally in your solution we could specify 1 or more wildcard domains like this:



I'm guessing the solution would be some regex to parse inbound requests and quickly pass or reject.

awarded to dekkard

Crowdsource coding tasks.

3 Solutions


it can easily be done by adding if condiition in your configuration file :

set $test 1;
if ($request ~* "") { #test for first path
    set $test 0;

if ($request ~* "") { #test for second path
    set $test 0;

if ($test = 1) { #if one of the previous test is not true
    return 403; #forbidden access

so if you have one of the words that matches in the request, you will not enter in the last condition that will set a 403 error.
Can you try this and give me a feedback ?

I guess if a supplied URL looks like or, it won't be blocked.
dekkard 1 year ago

This is not exactly what you have asked for, this solution is for preventing image hotlinking. It might be helpful for you. the problem with your request is anyone can access copy your proxy url and access the image.

location ~ .(gif|jpe?g|png)$ {
# Configurations to check for image hotlinking.
# Remember to substitute with your domain.    

valid_referers none blocked *;
if ($invalid_referer) {
   return 403;

Do let me know if it works for you.

I appreciate the thought, we have a CDN sitting in front of the proxy so it will be a bit blind to this part of the pipe. thx for the thought though!
Qdev 1 year ago
No problem :)
Zhopon 1 year ago
Winning solution

Here's the regex solution:

location ~* ^/.+/http.?://(?![^\/]*(source1\.com|source2\.com|whatever\.org)/).*$ {
  return 403;

I guess this should be the first "location" in config.
Here,,, are the trusted domains, which won't be blocked.

Tested this config with this tool

Test URLs and results: - ok - no match - ok - ok - ok - blocked - matches - blocked - blocked - blocked - blocked
worked perfect and was nice and elegant
Qdev 1 year ago
View Timeline