Score:0

How to redirect user if direct access image files by browser? [nginx]

cn flag

How do I redirect if a user tries to direct access image files in browser only? I want to keep the ability to embed images with <img src="...">. How to redirect from

https://img.example.com/c/600x1200_90_webp/img-master/img/2022/01/03/08/04/54/95259215_p0_master1200.jpg

to

https://example.com/detail?id=95259215

This is my nginx conf

location ~ "^/c/600x1200_90_webp/img-master/img/\d+/\d+/\d+/\d+/\d+/\d+/(?<filename>.+\.(jpg|png|webp))$" {
    return 301 https://example.com/detail?id=$filename;
}

Code isn't working cause it's going to https://example.com/detail?id=95259215_p0_master1200.jpg but I need it to trim the string after the last digit of the filename so in this case trim off _p0_master1200.jpg. I also don't know how to make it if user is accessing it through browser.

Score:0
us flag

Your regular expression (?<filename>.+\.(jpg|png|webp))$ captures the whole filename to the filename variable. To exctract only part before _ to variable, use the following instead:

(?<filename>[0-9]+).+(?:jpg|png|webp)$

This one only matches numbers for the filename variable (I would call it image_id to be more descriptive). https://regexr.com is a good tool for working with regular expressions.

For limiting display only to browsers, you need to use nginx http referer module.

These two combined, the configuration would look like:

location ~ "^/c/600x1200_90_webp/img-master/img/\d+/\d+/\d+/\d+/\d+/\d+/(?<filename>[0-9]+).+(?:jpg|png|webp)$" {
    valid_referers server_names;
    if ($invalid_referer = "0") {
        return 301 https://example.com/detail?id=$filename;
    }
}

nginx will check the HTTP Referer value. If it contains the name specified in server_name field, it will send the redirect. The referer field is set by browser when it loads resources for a web page.

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.