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?


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.
  • 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 clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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