Location context

Location context is used to map different urls paths within a domain (Similar to URL handling in django)

server {
      listen       80;
      server_name  www.wordpress.com;
      root   /usr/share/nginx/html/wordpress;

      # www.wordpress.com
      location / {
      }

      # www.wordpress.com/admin
      # seraches at root/admin/admin.html
      # use /admin.html, if the file was at the root
      location /admin {
          index  admin.html /admin.html;
      }

      # anything that ends in .jpg or .gif
      # ~ represents case-sensitive
      # .* any character except line break
      # \. special char needs to be prefixed with \
      # $ is end of string
      location ~ /wp/.*\.(jpg|gif)$ {
          return 404;
      }
    }

Resolving conflicts

1) location /admin/admin.html{return 200;} has higher priority than location /admin {return 404;}

2) location /admin/*.html{return 200;} has higher priority than location /admin/admin.html {return 404;} (Unless ^~ is used in the latter)

3) location = /admin/admin.html{return 200;} has higher priority than location /admin/*.html {return 404;}

Try files

Try a path, and if it doesn't exist, redirect to another

# try_files
  location /data {
    # if file path does not exist, return 403
    # try_files $uri =403;

    # if file path does not exist, render some html
    try_files $uri /404.html;
  }

Rewrite (point to different file)

Rewrite a URL (similar to redirect)

#rewrite
  location /rewrite {
    # ^ full location path (ie domain name/rewrite in this case)
    # (.*)$ everything after that
    # rewrite this string with something else   
    rewrite ^/(.*)$ /index.html?id=$1 break;
  }

alias (point to different root)

Point to a directory which is not accessed through root

# now the root will be /vol
    location /static {
        alias /vol/static;
    }

autoindex

List files in a directory.

By default, nginx sends 403 forbidden response when URL points to a directory(unles location is specified) (However, if the client knows the exact path of the files, they can still view it. ie, www.d.com/dowm may be forbidden, but www.d.com/down/file.txt will be viewable)

To explicitly list contents, set autoindex to on

# auto index
  # by default nginx does not allow viewing directories
  # www.wordpress.com/down/ ==> forbidden
  # to allow listing of files, use autoindex on
  location /down {
    autoindex on;
  }

Deny viewing of files in a directory

# deny viewing files in a directory 
  # without this, client could view the file if they know the exact uri
  # We have to forbid, www.wordpress.com/protected/secret.json
  location /protected {
    deny all;
  }