Your nginx
configuration looks mostly correct, but there are a few changes that you can make to ensure that it works as expected.
First, you need to define the actual whitelist of domains that are allowed to access the images. In your current configuration, you have defined two whitelisted domains as whitelist1
and whitelist2
. You should replace these with the actual domain names that are allowed to access the images.
Second, in your map context, you have defined the variable $whitelist
as the value of the subdomain that is making the request. However, what you actually need is the value of the domain name that is making the request, without the subdomain. You can modify your map context to extract the domain name as follows:
map $http_host $whitelist {
default 0;
"~^(?<subdomain>\w+)\.(?<domain>domain-name\.example\.com)$" $domain;
# whitelist domains
whitelist1 example.com;
whitelist2 subdomain.example.com;
}
In the example above, the regular expression captures the subdomain and the domain name separately. The variable $domain
is then set to the value of the domain name without the subdomain.
Finally, you can use the $whitelist
variable in your server block to determine whether to allow or deny access to the images. Your updated configuration would look like this:
map $http_host $whitelist {
default 0;
"~^(?<subdomain>\w+)\.(?<domain>domain-name\.example\.com)$" $domain;
# whitelist domains
whitelist1 example.com;
whitelist2 subdomain.example.com;
}
server {
listen 80;
proxy_intercept_errors on;
error_page 400 = @fallback;
if ($whitelist = 0) {
return 403;
}
location /images {
# allow access only to whitelisted domains
allow $whitelist;
deny all;
# serve images from disk
alias /path/to/images;
}
location @fallback {
# handle errors
return 400;
}
}