0

I did a little rewrite rule a little while ago to redirect ppl who directly access my site's image to image pages instead,

for example a person accessing www.mysite.com/i/asdf.jpg to www.mysite.com/pic/asdf

this is the rewrite rule i used :

location /i/image_(\d+).(gif|jpg|jpeg|png)$ {
  root /home/mysite/public_html;
  valid_referers www.mysite.com mysite.com;
  if ($invalid_referer) {
   rewrite ^ http://www.mysite.com/pic/$1 permanent;
  }
 }

I made a subdomain of the directory 'i' which contains all the images. so its like thsi now http://i.mysite.com/

Is it possible to make a rewrite like the one above so if the file is directly accessed by a different referer via subdomain it will hit the same rewrite rule ?

I tried this in the subdomain server{...} :

location /image_(\d+).(gif|jpg|jpeg|png)$ {
  root /home/mysite/public_html/i;
  valid_referers www.mysite.com mysite.com;
  if ($invalid_referer) {
   rewrite ^ http://www.mysite.com/pic/$1 permanent;
  }
 }

but no luck so far :( thx :)

1 Answer 1

0
location /i/image_(\d+).(gif|jpg|jpeg|png)$ {
  root /home/mysite/public_html;
  valid_referers www.mysite.com mysite.com;
  if ($invalid_referer) {
   rewrite ^ http://www.mysite.com/pic/$1 permanent;
  }
 }

$1 in the rewrite's replacement is used to back reference to rewrite's regex, not location's regex. The regex in location directive can be captured in alias, error_page, ...

Try the following:

server {
        server_name i.mysite.com;

        access_log /var/log/nginx/i.access_log main;
        error_log /var/log/nginx/i.error_log info;

        location / {
            root /home/mysite/public_html/i;
            valid_referers www.mysite.com mysite.com;
            if ($invalid_referer) {
                rewrite ^/image_(\d+)\.(gif|jpe?g|png)$ http://www.mysite.com/pic/$1 permanent;
            }
        }
    }

You also must escape the dot with a backslash.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .