How do I redirect if a user tries to direct access image files in browser only? I want to still keep the ability to allow social media sites to embed our images by hotlinking. I just want only if a user direct access image by browser to redirect.
This is my nginx conf
proxy_cache_path /var/www/img.example.com/htdocs/cache-store levels=1:2 keys_zone=pixstore:10m max_size=5g inactive=7d use_temp_path=off;
server {
server_name img.example.com www.img.example.com;
access_log /var/log/nginx/img.example.com.access.log ;
error_log /var/log/nginx/img.example.com.error.log;
add_header X-Proxy-Cache $upstream_cache_status;
location / {
proxy_cache pixstore;
proxy_cache_revalidate on;
proxy_cache_use_stale error timeout updating http_500 http_502 http_503 http_504;
proxy_cache_lock on;
add_header X-Cache-Status $upstream_cache_status;
proxy_pass http://xxx.xxx.xxx.xxx:8090;
proxy_redirect off;
include proxy_params;
proxy_cache_valid 200 7d;
proxy_cache_valid 404 5m;
}
location ~ "^/c/600x1200_90_webp/img-master/img/d+/d+/d+/d+/d+/d+/((?<filenum>d+)[^/]+.(jpg|png|webp))$" {
valid_referers server_names;
proxy_pass http://xxx.xxx.xxx.xxx:8090;
if ($invalid_referer = "0") {
return 301 http://view.example.com/artwork/$filenum; }
}
}
The redirect isn’t working. How can I fix this?
3
Answers
I think you would be a lot better off doing it with something like Node.js and testing the User Agent string against a regular expression and if it contains something that browsers have like the text "Chrome" "Firefox" etc in it then redirect.
How about whitelisting social media’s agent IP instead?
For example, this is how you find all IP address used by Facebook’s agent
then add this to your nginx conf
And perhaps, you may want to check you regex using this site
I would consider referer. Here is nginx module, and here is an article with some explanation, and gist with piece of code. So basically – you need to have the module and then you can use something like this:
Where
example.com
is your domain. Let me know how it goes – I’ll update answer if needed.