Sign up ×
Server Fault is a question and answer site for system and network administrators. It's 100% free, no registration required.

Trying to convert over an apache config to nginx.

<Directory /usr/local/image/>
 Order allow,deny
 Allow from all
Alias /key1 /usr/local/image
Alias /key2 /usr/local/image
RewriteEngine On
RewriteCond /usr/local/image/$1 !-f
RewriteRule ^\.(jpg|jpeg|gif|png))$ /handler.php

so a request to /key1/subdir1/subdir2/123.png OR /key2/subdir1/subdir2/123.png would look to /usr/local/image/subdir1/subdir2/123.png, serve it if it exists, or go to /handler.php if not (404)

I've tried:

    location ^~ /key1 {
     alias /usr/local/image/;
     error_page 404 /handler.php;

Which somewhat works - but I would like to limit this rule to only images (jp?g|gif|png) but the subdir1 & subdir2 values will vary.

Any suggestions on how to efficiently do this in nginx?

share|improve this question

1 Answer 1

up vote 1 down vote accepted

Try this:

location ~* /key[12]/(.*\.(jpe?g|gif|png)) {
    alias /usr/local/image/$1;
    error_page 404 /handler.php;

PS: I use ~* for case insensitive matching.


If your two aliases are completely different, you can put it into round brackets:

location ~* /(?:abc12345|12abcdef)/(.*\.(jpe?g|gif|png)) {
    alias /usr/local/image/$1;
    error_page 404 /handler.php;
  • a question mask colon ?: at the beginning of the group means not counting for back reference.
share|improve this answer
nice - if the two keys were significantly different (say /abc12345 & /12abcdef) would you split them into two different location statements? – jimg Sep 12 '11 at 12:16
You can put it into round brackets. Please check out my above edited answer. – quanta Sep 12 '11 at 14:09

Your Answer


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.