Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

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 :)

share|improve this question
add comment

1 Answer

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.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.