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

I'm wondering whether this is possible with Nginx: I just added a directory with a bunch of HTML files (foo.html, bar.html) that I'd like to serve with /foo, /bar, etc. If the URL doesn't match up with a file name I'd like to fall back to whatever the next best matching location would be.

So I have:

  # This block is newly added.
  location ~ ^/([^/]+)$ {
    default_type text/html;
    alias /blah/$1.html;
  }

  # Our long list of existing subsystems below....
  location /subscribe {
    proxy_pass http://127.0.0.1:5000;
  }

  location /upload {
    proxy_pass http://127.0.0.1:8090;
    proxy_read_timeout 99999;
  }

  location ~ /(data|garbage|blargh).* {
    proxy_pass http://127.0.0.1:8090;
    proxy_read_timeout 99999;
    auth_basic text;
    auth_basic_user_file /etc/nginx/htpasswd;
  }

  ....

The problem is that the first regex now eats up the URLs that would've gone to other locations, as per the documented behavior of location.

One approach is to maintain the full explicit list of files in the first location block, but this list is quite large and is always changing. Is there a way to check to see if the file exists first, and if not, then continue with what would've been the next-best location match?

I took stabs using try_files (including using a @fallback and nesting locations in there) but I don't think it's capable of doing this. However I thought I'd ask here in case I'm missing something. (Or maybe there's another better approach altogether.)

share|improve this question

1 Answer 1

location / has the lowest priority anyway, so I'd use try_files and this trick:

    root /ngx/html/s;
    location / {
        try_files $uri.html /s$uri;
    }
    location /s {
        internal;
        root /ngx/html;
    }
share|improve this answer

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.