Chapter

Location matching

How nginx picks which location block handles a request, plus try_files, redirects, and rewrites.

Nginx Basics 5 Lessons from courses

About this chapter

A single request can match several location blocks. This chapter shows the exact rules nginx uses to pick one, and the tools you use inside a block to check files, redirect paths, and rewrite URLs.

Lessons from courses

  1. 1 How location matching works The five nginx location match types - prefix, exact =, regex ~ and ~*, and ^~ - and exactly which URLs each one matches, with clear examples.
  2. 2 Matching priority The exact nginx location priority order: exact = first, then ^~, then regex in file order, then longest prefix. Worked examples that clear up the confusion.
  3. 3 Serving files with try_files How nginx try_files checks if a file exists, falls back to a folder index, and returns 404 - plus the front-controller fallback pattern for real sites.
  4. 4 Redirects with return Set up an nginx redirect with return 301 and 302 - move a single path or a whole domain, keep the query string, and know why return beats rewrite.
  5. 5 Rewrite basics How nginx rewrite rules work with regex captures and the last, break, redirect and permanent flags, plus when to use rewrite instead of return.
Nginx Basics Go to course