Server Fault is a question and answer site for system and network administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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 {

  location /upload {
    proxy_read_timeout 99999;

  location ~ /(data|garbage|blargh).* {
    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

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 {
        root /ngx/html;
share|improve this answer

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.