Ravindra BagaleCourses & study guides मराठी Track your progress

Chapter 8: Configuring Nginx and Apache

AWS Cloud

8.2 Reading an Nginx configuration

In short: Nginx configuration is made of directives (name value;) and blocks (name { ... }), also called contexts.

Friends, an Nginx config is made of directives and blocks. Once you understand these four or five directives – listen, server_name, root, index, location – you can read any server block.

Nginx configuration is made of directives (name value;) and blocks (name { ... }), also called contexts:

main context  (user, worker_processes, error_log)
 ├── events { worker_connections ... }
 └── http {  (mime types, logging, gzip, include conf.d/*.conf)
        └── server {            ← a virtual server for one or more names
               listen ...; server_name ...; root ...;
               └── location /path { ... }   ← rules for part of the URL
            }
     }

A fully commented server block:

# /etc/nginx/conf.d/mysite.conf   (Ubuntu: /etc/nginx/sites-available/mysite)
server {
    listen 80;                          # IPv4 port
    listen [::]:80;                     # IPv6 port
    server_name example.com www.example.com;   # which Host names this block answers

    root  /var/www/mysite;              # document root: URL "/" maps here
    index index.html index.htm;         # file served for a folder request

    location / {
        try_files $uri $uri/ =404;      # file? folder? otherwise 404
    }

    location /images/ {
        expires 7d;                     # let browsers cache images for 7 days
    }

    error_page 404 /404.html;           # custom error page (file inside root)
    autoindex off;                      # never list folder contents

    access_log /var/log/nginx/mysite_access.log;
    error_log  /var/log/nginx/mysite_error.log;
}
Directive What it does Example
listen Address and port for the listener. default_server marks the fallback for that listener. listen 80 default_​server;
server_name Matches the requested hostname. _ has no built-in fallback behavior. server_​name example.​com www.​example.​com;
root Folder that URL paths are appended to root /​var/​www/​mysite;
index File(s) to try for a folder URL index index.html index.htm;
location Rules for matching URL paths location /​api/ { ... }
try_files Try files in order, then fall back try_​files $uri $uri/ /​index.​html; (SPA)
return Send a redirect or status immediately return 301 https://example.com$request_uri;
error_page Custom error page error_​page 404 /​404.​html;
client_​max_​body_​size Maximum request body size (default 1m) client_​max_​body_​size 20M;
server_tokens Show/hide Nginx version in headers and error pages server_​tokens off;

The two classic Nginx syntax errors

A simple directive ends with a semicolon ;. A block opens with { and closes with }. When nginx -t reports a syntax error with a file and line, check the indicated statement, its predecessor and the surrounding braces.

How Nginx chooses the server block

  1. It determines which listen address and port accepted the request.
  2. For ordinary HTTP name matching, Nginx looks for an exact hostname, applicable wildcard forms, then the first matching regular expression.
  3. When no name matches, it uses the default_server for that address and port. Without an explicit default, it uses the first server defined for that listener.

That rule explains the most common complaint: "I configured my site but I still see the welcome page." Some other block won, because it is the default or because your server_name doesn't match what the browser sent.

Ravindra Bagale's Tip

Many students write server_name http://example.com; with http://, and the block never matches. Put only the host name in server_name: server_name example.com www.example.com;. And if the welcome page shows up, first check which block is the default_server.

Lab

On a practice listener, compare two GET requests to the same address and port while changing only the requested hostname. Inspect the status, body marker and correctly scoped access log. The isolated lab below provides predictable controls.

Read the configuration with one request in mind

Imagine you maintain a workshop website with printable notes and a separate library site that shares the same Nginx process. A student opens the workshop homepage and gets the correct course name. They click a link to a file named notes.txt and receive a short explanation instead of the file. A second student pastes the server's bare IP into a browser and sees a different page. The server can accept all three requests without making the same decision for each. To understand the behavior, start with the connection destination, the name supplied by the client, and the URL path. Trace them through two selections before considering the content on disk.

Nginx is a program that can accept HTTP requests, serve public files, or send requests on to another program. Its configuration describes the decisions to make. A directive is one instruction. A simple directive supplies arguments and ends in a semicolon. A block encases related instructions in braces. The enclosing scope, or context, tells you which instructions apply there. It also determines which directives are legal. Think of a main timetable for the whole training center, a separate timetable for the library, and a set of registration rules for one desk. You need the right level to know whether a particular rule applies to a student.

In an ordinary HTTP configuration the top level is the main context. An events block deals with connection processing options. An http block contains settings for HTTP. A server block inside it can describe a virtual site for one or more names and listeners. A location block inside the selected server groups rules for a path. File boundaries matter when searching, but your reading sequence is about these nested contexts. An include physically stored in a separate file is read at the point where the include directive appears. The included text still has to make sense in that context. A site file containing a whole server directive can belong inside http. Moving that file to an include within an existing server block would put a server declaration in the wrong scope.

main context
  events block
  http block
    included site file
      server block for workshop.test
        location matching /guides/
        location matching /assets/
      server block for library.test

Practice reading from the outer level inward. First find the process's entry configuration using the configuration discovery lesson. Then identify the HTTP list of servers that came from that entry and its includes. Next decide which server the connection and name select. Finally follow the location, file mapping and response behavior within that server. This ordering saves you from seeing an attractive root line in a text search and assuming it governs the student request. Two public sites can have the same URI path yet different content roots. Two locations within one site can also use distinct rules.

Start with a concrete request record. The small training example uses HTTP at 127.0.0.1:18882 with the request hostname workshop.test. One request asks for /guides/intro.html?print=1. The scheme HTTP describes the protocol. The destination address and port tell the connection where it should land. The hostname identifies the virtual site the client wants. The part before the question mark is the path. The value after the question mark is the query string, which can supply an option to an application. Location matching uses Nginx's normalized URI path rather than that query string. In this example adding print equals one does not select a different location just because the query changes.

Work the example forward in plain words. The listener at that address and port accepts the connection. Its eligible server definitions are candidates. The workshop name selects the workshop server. The longer path prefix for guides selects the guides location if no more specific rule wins. The file lookup uses the normalized path and whatever root is effective there. A matching file returns the workshop guide. A request with the same path and the library name can reach the library site and return its own guide. A request to the same port for an unknown name can reach a deliberately separate fallback. Each result has a reason you can check against its own inputs.

First select the listener and virtual site

A listener represents where the server accepts connections. The accept point includes a local address and port. An Nginx listen directive can specify both. A configuration may also use a wildcard address to listen on more than one interface, and can have separate IPv4 and IPv6 listeners. A port number alone is incomplete when there are multiple addresses. Two named servers can share the same listener as candidates to answer HTTP at that endpoint. They do not need separate public IPs, separate programs or separate ports merely because they serve different hostnames.

Within that listener, Nginx compares the request hostname to the names declared in server_name. With ordinary plain HTTP the Host header commonly provides that name. If a client sends an exact name matching a site on the listener, that is normally the easiest rule to follow. An exact name wins before wildcard forms. Nginx checks the longest relevant leading-asterisk wildcard before ending-asterisk wildcard names, then uses the first matching regular expression name in declaration order. A regular expression is a more expressive pattern for matching text. A wildcard or regular expression is useful only where it models names the operator intends to serve. Begin a small exercise with exact names so every selection is visible.

Keep the default associated with the listener. A server can be marked as its explicit default. When a valid request has no configured name match, Nginx can fall back to that server. If there is no explicit default, the first server for the relevant address and port is the default. A conventional underscore written as a server name has no special catch-all power. The fallback behavior in this lab is declared by the default parameter on listen. A separate default returning an unmistakable status and small body gives you a control. The workshop cannot accidentally appear to work by serving its own ordinary content for the wrong hostname. For a public service, its owner chooses whether a fallback should respond, redirect to an approved canonical name, or decline the request.

Suppose the training site is listed as library on port 18882, workshop on the same address and port, and a preview version of workshop on another local port. A request for workshop on 18882 cannot select the preview definition merely because the name is identical. Its address and port first selected another listener. Conversely a request for workshop.test and a request written as the numeric IP may share an endpoint while selecting different host definitions. When you probe, keep a written record of both layers. Replacing a hostname with an IP inside the URL changes the request's authority as well as bypassing ordinary name resolution.

HTTPS adds a connection setup step before the server reads the HTTP request. During TLS, a client typically sends the desired server name using Server Name Indication, or SNI. That gives the listener a name to choose an appropriate certificate before the HTTP headers arrive. The HTTP host later influences request-level routing. For diagnosis, use the same intended HTTPS hostname in the URL and override its resolution to a known address if appropriate. A header override that reaches the HTTP phase cannot repair a certificate chosen earlier for the wrong name. The isolated lab uses plain HTTP on loopback so you can see the hostname and path effects without a certificate setup.

Observe the result that belongs to the site. The server header commonly identifies the server software but can be the same across all locally configured sites. A body marker such as library-guide gives you a stronger control. An access log format may include the received host and the selected server name. Those fields answer different questions. If the request goes to an explicit default, the requested name can remain the original unknown probe while the selected server value refers to the default definition. Use both when explaining a mismatch.

Then select the location and request handler

Once the server is selected, focus on the request URI. The applicable location can serve content, return a status directly or send the request elsewhere. The location declaration is a match rule over the path. It does not name a starting folder unless another directive maps that path to disk. An exact match, a prefix match and a regular expression match can all be visible in one server. A prefix is the opening part of a path. A request for /guides/intro.html begins with /guides/, so that prefix is a candidate. Including its final slash prevents it from matching something like /guideshop/intro.html.

For a straightforward server with top-level exact, prefix and regex locations, read selection as a small decision table. The lab uses those common forms. If your installed version uses additional matching forms, consult the documentation for the actual configuration. An exact location declared with equals ends the search when it matches the path. Otherwise Nginx remembers the longest matching prefix. If that prefix has the caret-and-tilde marker, the regular expression search is skipped. Otherwise Nginx tests regex locations in order and uses the first one that matches. If none matches, it returns to the remembered prefix. Nested locations can complicate the trace. This lesson keeps the rules at one level so you can check each selection by sending a request. Rule order matters for regex matches and is a poor substitute for reasoning about prefix lengths or exact matches.

Predict matching for the flat workshop configuration
PathCandidate rulesExpected result
/guides/intro.htmlRoot prefix and guides prefixGuides prefix, no regex match
/guides/exact.txtExact rule, guides prefix and text regexExact rule ends the search
/guides/other.txtGuides prefix and text regexText regex wins after prefix selection
/assets/handout.txtAssets prefix marked to skip regex and text regexAssets prefix, regex search skipped
/notes/Notes prefix at first, then the internally selected file pathAfter index selection, the text regex can match the new URI

The important surprise is that Nginx can make a new location decision during the same request. An internal redirect is a change to the URI being handled by the server without asking the browser to send a new request. The index module may internally redirect a directory request to its selected index file. In the lab the workshop notes folder contains index.txt. The request path ending in a slash can match the notes prefix first. The index directive chooses index.txt. Nginx then handles /notes/index.txt, which can match the text pattern. The browser still reports the original URL even though the final response came from a location that did not match the original slash-terminated path.

An external redirect has a different observation. The response status is a redirect and its Location header tells the client where to request next. A client may follow that instruction automatically when asked to do so. To distinguish the two events, inspect the initial status and headers without following redirects. If the status is successful and no redirect is visible, yet an index file falls into another handler, the behavior can be a server-internal choice. If you see a redirect status with a Location header, test its destination separately. The first and following requests introduce two distinct opportunities to select a location or even a different virtual site.

The lab's exact rule and its regular expression return their own short text. They make the chosen handler easy to observe without relying on a filesystem permission fault or a missing file. When reviewing a production configuration, a response generated by return should stop you from assuming the requested content file was opened. Likewise, a proxy rule may send work upstream, a term for an application behind this web server. Identify the response mechanism once you know the selected location. The next lens is the difference between serving a real file and defining how the URI is handled.

Map the selected path to a file or a response

A document root is a directory that acts as the starting point for many static-file lookups. A static file is prepared in advance and can be sent directly, such as an image or a plain study guide. When the effective root is /srv/training/workshop, the normal root mapping for the URI /guides/intro.html produces the path /srv/training/workshop/guides/intro.html. Root takes the complete URI path. It does not remove the matched prefix. A root declared in one location can override a broader root for matching requests, so connect the rule to the location before computing the disk path.

There is another directive called alias with different mapping behavior. In a simple prefix location, an alias can replace the matched part of the URI with another directory. For example, an alias at /published/ to a directory ending in /shared/ would use the remaining filename under that shared directory. Read the exact setting before calculating either path. Sending a request to a prefix and finding files in a similarly named disk folder does not show which mapping made them available. The document root lesson continues this distinction with a separate change and rollback exercise.

A directory request can cause the index module to search for a default file. If you request the folder teachers normally use by opening the folder URL with a trailing slash, the configured index names are tried in order. A file extension such as PHP in the index list does not create a language runtime. Executing PHP requires routing to a configured PHP handler, such as FastCGI backed by PHP-FPM. The lab uses ordinary text and HTML files because they can be served directly and give you an unambiguous content marker. If an index is missing, inspect the configured handling for that directory. A denied directory or an unlisted directory with no permitted index can lead to different results from a missing ordinary file path.

The try_files directive checks specified candidates in order in the current context. A literal final status such as 404 gives the request a clear result when none of the requested file or directory candidates exists. A final URI can perform internal routing to another place in the configuration. Both choices can be valid, depending on the application. A static note archive should normally return a real missing-file status when a PDF is absent. A front-end application that uses browser-side routing may intentionally send some unknown page routes to its application shell. Using that fallback for an asset directory as well can conceal missing JavaScript behind a successful HTML response. Reading try_files means tracing both the working file path and the fallback branch.

File and folder probes answer different questions. If the target is /guides/intro.html, check the response marker for the intended file. If the target is /notes/, follow index selection and possible rematching. A command that asks only for response headers can be useful for caching or redirect diagnosis, but it cannot distinguish two successful bodies on its own. For this lab, use GET with curl's display of headers and body. Keep the URL, hostname, port and suffix visible in your notes. Changing a missing URI into an existing one makes a positive control, which you can compare to the intentional missing case.

Some directives change timing or headers instead of selecting the body. In a basic images location, expires can set response caching headers for eligible responses. A fresh browser or shared cache can later return bytes without hitting the same origin request, so an origin check and a normal browser check answer distinct questions. Similarly, server_tokens set to off can withhold version details from common server-generated output but does not turn an Nginx web server into another product or provide access control. Attach a directive to the particular behavior it controls. No one line establishes all aspects of a site's response.

Lab to predict and test eight Nginx branches

Use a regular account on a disposable practice machine with Nginx, Bash and curl. The lab opens one private loopback listener on 18882 and keeps its configuration, process identifier, logs and files in a temporary directory. Leave the public services and system configuration alone. Pick another unused unprivileged port and replace every 18882 in this lab if that port is already occupied. Work in one disposable Bash shell so the directory and child identifier remain available for cleanup. The exact lab below was tested against a separate local Nginx build. A package with unusual module switches or compiled paths can require adjustments.

The preparation creates three informative content markers and a separate short notes index. The workshop guide and the library guide have exactly the same relative disk path but different main directories. The workshop assets file demonstrates a prefix kept ahead of the regex. The notes index serves a negative teaching control: a file exists, but a subsequent handler is expected to send a synthetic answer instead. Predict each result before starting the process.

if [ "$(id -u)" -eq 0 ]; then
  printf 'Use an unprivileged practice shell.\n' >&2
  exit 1
fi
nginx_lab=$(mktemp -d /tmp/rb-nginx-reading.XXXXXX) || exit 1
nginx_bin=$(command -v nginx) || { rmdir "$nginx_lab"; exit 1; }
lab_pid=
reading_cleanup() {
  if [ -n "$lab_pid" ] && kill -0 "$lab_pid" 2>/dev/null; then
    kill -QUIT "$lab_pid"
    wait "$lab_pid" 2>/dev/null || :
  fi
  case "$nginx_lab" in
    /tmp/rb-nginx-reading.??????) rm -r -- "$nginx_lab" ;;
  esac
}
trap reading_cleanup EXIT
mkdir -p "$nginx_lab/workshop/guides" "$nginx_lab/workshop/assets" \
         "$nginx_lab/workshop/notes" "$nginx_lab/library/guides"
printf 'workshop-guide\n' > "$nginx_lab/workshop/guides/intro.html"
printf 'library-guide\n' > "$nginx_lab/library/guides/intro.html"
printf 'workshop-asset\n' > "$nginx_lab/workshop/assets/handout.txt"
printf 'physical-note-index\n' > "$nginx_lab/workshop/notes/index.txt"

Now write the complete configuration to that root. The quoted here-document marker asks Bash to preserve expressions such as the dollar-prefixed Nginx variables exactly as written. The program uses the relative filesystem paths under the prefix selected at invocation. The error log, PID, and temporary-body directories belong to this copy. The explicit default sends a 404 body with a predictable marker. The named workshop and library then share the same endpoint.

cat > "$nginx_lab/nginx.conf" <<'NGINX'
worker_processes 1;
pid nginx.pid;
error_log error.log notice;
events { worker_connections 32; }
http {
    client_body_temp_path body;
    proxy_temp_path proxy;
    fastcgi_temp_path fastcgi;
    uwsgi_temp_path uwsgi;
    scgi_temp_path scgi;
    default_type text/plain;
    log_format choices '$server_name "$http_host" "$request_uri" "$uri" $status';
    access_log access.log choices;

    server {
        listen 127.0.0.1:18882 default_server;
        server_name fallback.test;
        return 404 "no-configured-host\n";
    }
    server {
        listen 127.0.0.1:18882;
        server_name workshop.test;
        root workshop;

        location = /guides/exact.txt {
            return 200 "exact-guide-rule\n";
        }
        location /guides/ {
            try_files $uri $uri/ =404;
        }
        location ^~ /assets/ {
            try_files $uri =404;
        }
        location /notes/ {
            index index.txt;
        }
        location ~ \.txt$ {
            return 200 "text-regex-rule\n";
        }
        location = /old-guide {
            return 302 /guides/intro.html;
        }
        location / {
            try_files $uri $uri/ =404;
        }
    }
    server {
        listen 127.0.0.1:18882;
        server_name library.test;
        root library;
        location / { try_files $uri $uri/ =404; }
    }
}
NGINX
"$nginx_bin" -e stderr -p "$nginx_lab/" -c "$nginx_lab/nginx.conf" -t

Read the test result before you start anything. The prefix option identifies the temporary root and the configuration option names its main file. The lowercase test option reads the candidate configuration. For the test, startup logging also goes to standard error rather than assuming a build-specific log directory. A positive syntax result means the parser understood the config and passed its checks. It cannot tell you which rule will match a request or whether the marker you expect is present. Include that distinction when documenting why you ran both the syntax test and actual HTTP probes.

"$nginx_bin" -e stderr -p "$nginx_lab/" -c "$nginx_lab/nginx.conf" -g 'daemon off;' &
lab_pid=$!
for attempt in 1 2 3 4 5 6 7 8 9 10; do
  if [ -s "$nginx_lab/nginx.pid" ]; then
    break
  fi
  if ! kill -0 "$lab_pid" 2>/dev/null; then
    break
  fi
  sleep 0.2
done
if ! kill -0 "$lab_pid" 2>/dev/null ||
   [ ! -s "$nginx_lab/nginx.pid" ] ||
   [ "$(tr -d '[:space:]' < "$nginx_lab/nginx.pid")" != "$lab_pid" ]; then
  printf 'The isolated listener did not start. Check its output and choose a free port.\n' >&2
  exit 1
fi

The startup command keeps the Nginx master in the foreground of the child process that your shell backgrounds. This lets the shell retain the identifier needed later. The wait loop gives it a brief chance to write the lab PID. Comparing the contents of that file to the shell's child prevents a stray file or other listener from being accepted as evidence that the lab started. A bind error here means investigate whether the port is already occupied rather than stopping the owner of that port. A private temporary path also makes it simple to see which logs and process files belong to this exercise.

probe() {
  local name=$1 path=$2
  printf '\n%s %s\n' "$name" "$path"
  curl --noproxy '*' --max-time 5 -sS -i \
    --resolve "$name:18882:127.0.0.1" "http://$name:18882$path"
}
probe workshop.test '/guides/intro.html?print=1'
probe library.test '/guides/intro.html'
probe workshop.test '/guides/exact.txt'
probe workshop.test '/guides/other.txt'
probe workshop.test '/assets/handout.txt'
probe workshop.test '/notes/'
probe unknown.test '/guides/intro.html'
probe workshop.test '/old-guide'

tail -n 8 "$nginx_lab/access.log"

Each transfer connects to the same local address and port and uses the hostname in its own URL. Each line printed just before the transfer identifies the variables you set. The bound timeout avoids a prolonged wait. Since the command includes headers and body and does not follow redirects, the original response can be matched to the request without ambiguity. A redirect display should contain a Location header that ends in the target guide. You can send another GET to that target as a separate control. The browser normally follows redirections, so observing the initial response with curl can expose a decision that would otherwise be invisible.

The expected workshop guide and library guide should have different marker bodies even though both paths reach the same listener. The exact path ends the search before the text expression. The guides path for other dot txt hits the regex rule. The assets file returns its disk marker because the longest prefix tells Nginx to skip the regex search. For the folder under notes, the index file does exist, but the internal destination matches the text rule. The unknown hostname reaches the fallback and gets 404 with no-configured-host. The final old-guide URL returns 302, proving it initiates a client-visible redirect.

On the last log line for the notes request, expect the requested URI and the final URI to differ. The log format explicitly prints both values. With the query example the request URI includes the query string while the current normalized URI maps the guide path. Your log may show the port as part of the received Host header. The first logged field is the selected server's configured name, useful for distinguishing the fallback from the name entered by the student. These observations give you more than a syntax result. They let you predict how one socket and one server process vary behavior according to the request.

For a second pass, restrict the text rule to the guides directory. This optional step needs Python 3 and runs before cleanup. It copies the existing lab instructions, then verifies that the expected pattern appears exactly once before replacing it. That check makes the example stop rather than making an ambiguous edit. The backup sits outside any include because this lab has one explicit entry file. A syntax test runs before sending the reload signal to the same confirmed child.

cp -p -- "$nginx_lab/nginx.conf" "$nginx_lab/pre-change.conf"
if python3 - "$nginx_lab/nginx.conf" <<'PY'
from pathlib import Path
import sys

config = Path(sys.argv[1])
source = config.read_text()
before = r"location ~ \.txt$ {"
after = r"location ~ ^/guides/.*\.txt$ {"
if source.count(before) != 1:
    raise SystemExit("Expected one original text location")
config.write_text(source.replace(before, after))
PY
then
  "$nginx_bin" -e stderr -p "$nginx_lab/" -c "$nginx_lab/nginx.conf" -t && kill -HUP "$lab_pid"
fi

Run the probe for the notes folder again. After the new configuration activates, it should return physical-note-index. Repeat the guides, exact, assets and library probes as controls. A signal asks the master to reload, and a request made immediately afterward may still see an older worker's result. Allow a short bounded retry and inspect the private error log if the result never changes. The fact that one branch changes while its controls hold is stronger evidence than seeing any 200 status after reload.

reading_cleanup
trap - EXIT
test ! -e "$nginx_lab" && printf 'Isolated Nginx lab removed.\n'

Save your table of observations before cleanup if you need it for class. The routine sends a graceful stop signal only to the child launched by your shell and removes only the temporary folder it created. The final test checks that the folder no longer exists. Should an earlier command fail, read the private error output before leaving the shell so you can distinguish a bad configuration line from a port conflict. The on-exit routine will otherwise remove the diagnostic files that belong to the exercise.

Use a response to narrow a configuration problem

There are at least three stages at which this configuration can surprise you. The parser can reject a file before the worker ever uses it. A valid configuration may select a different server or location from the one you expected. The right location can begin work and then report a missing file, permission problem or upstream failure. Begin by determining which stage produced an observation. A syntax message names a local checking operation. A refusal or timeout came from making a connection. An HTTP response already means some service handled enough of the request to send a protocol answer. A location interpretation begins after you know which listener it reached.

When a parser reports an unexpected brace, read the entire surrounding statement and context. The parser might only notice a missing semicolon when it reaches the next token. Start at the reported file and work back through that directive and the braces enclosing it. A directive says where it is legal. For example, an ordinary server block would be misplaced at the top level if it was supposed to be included inside HTTP. A suggestion to add punctuation everywhere can create new parse failures. Change the single syntactic cause and test the same entry configuration again so you know the fix did not bypass the file that was failing.

When the parser passes and the HTTP body is unexpected, examine a small contrast. If workshop and library both return the fallback body, test a known correct authority against the same address and port. Make sure the intended named servers are included in the dump and share the listener you reached. If the workshop guide works but the workshop handout does not, keep the name fixed and inspect path selection. Probe an exact path, an ordinary file under the same prefix, and the disputed path. In this lab successful status for all three does not imply all three routes serve disk content. The labels identify the actual differences. That matters when permissions, access logs and caching differ by route even though a browser displays text in both cases.

Suppose a trainer asks to restrict the dot txt behavior to guides only. A single intentional change would narrow the existing expression to paths beginning with the guides prefix and ending in dot txt. Predict which probes would change. The notes folder should begin returning the actual file marker after its index selection no longer matches the expression. The ordinary guides text request should still get the synthetic response. The exact guides path should stay exact. The assets marker should remain, because the chosen prefix continues to bypass the regex. The library is a separate server and should keep serving its own guide. This prediction specifies a target, several controls and a rollback condition before you edit.

Read the access log with more care than a summary status alone. In an access log configured for request completion, a log line describes the resulting context and selected values. A log written under one location can reflect the final location even if the request began elsewhere. The lab records the original request URI separately from the final URI. In a real service, use the log fields actually configured for that site. A shared log without a host or marker can be ambiguous when the same path is common. Adding appropriately scoped fields to an authorized diagnostic configuration can help, but avoid recording query data that can carry private information or signed tokens.

Caching can account for another difference. Suppose the direct origin returns a new guide marker after a valid reload while a browser still shows the saved earlier content. The direct request is a useful origin control, and the cache headers and browser's request details can tell you whether it reused data. Run the direct request with the same authority and path as before. Record whether the public edge sees the same change before treating it as a disk or location error. Restarting a healthy origin would not clear a response in a separate browser or cache. Use the observations to identify the actual system that made the stale choice.

Think through the most important rollback test as well. Reloading instructions changes a rule, while deploying files changes what paths can be read. If you change both at once and the route is wrong, diagnose with a verified original configuration and known content markers rather than starting over from empty directories. The chapter's later safe-change workflow expands this into a repeatable procedure. In the meantime, teach yourself to state one testable hypothesis per adjustment. A good hypothesis names the matched listener, request hostname, URI, expected rule and resulting marker or status.

Practice by changing one input at a time

Build a results sheet for the eight supplied probes. Write the expected server, the initial path, any internal destination, the final handler, the status, and the body marker or redirect target. Compare it to the actual CLI output. A completed sheet accurately distinguishes the query string preserved in the original request URI from the URI that controlled matching. It also separates the final server-chosen notes handler from the old guide's client-visible redirect. Explain how each distinguishing observation would still be available to a colleague with no browser cache or access to the underlying files.

Run a missing-guide control during a second, clean lab run. Request a name ending in html under the workshop guide prefix that has no corresponding file and no directory. Predict a 404 from the valid named site. Compare it with the 404 sent by the unmatched-host server. Their status numbers agree, but the latter body contains the explicit fallback marker and its server name appears in the log. Then use a nonexistent name ending in dot txt under the same guide prefix. The text expression can still return its synthetic response. Explain why a successful file lookup was unnecessary in that third request.

For a more challenging reading exercise, sketch a revised configuration containing an explicit error page. Suppose a misplaced error page itself lives under the regex match. Trace the failed lookup and the subsequent internal error destination. Predict what you need to inspect to tell whether the final body is the intended error template. Sketch the equivalent for a location serving a front-end application's fallback page. The exercises share an ability to rematch a path internally. They differ in how the response status should be treated. Try the actual lab first so the concepts are attached to real outputs before you design a second config.

After a colleague reads your notes, ask them to pick one request and explain it back to you with the config lines visible. If their explanation works only because they remembered the results table, ask them what would happen if the hostname or suffix alone changed. A useful interpretation predicts differences. It also states the limit of a loopback lab. The plan exercises HTTP behavior on this one machine. External routing, certificate choice on a public listener and any upstream proxy need separate evidence when present.

Interview questions, quiz and revision cards

What is the difference between a listen setting and a server name?

Listen identifies an address and port on which the site can receive traffic. Several server blocks can share that endpoint. The server name helps select the appropriate virtual site among candidates when a request carries a name. A name written in a block with the wrong listener cannot fix a user connecting elsewhere.

Why can an exact path win over a regex that also matches?

An exact location terminates the location search in this flat configuration. The text regex's position in the file does not matter for that exact path. A nearby path with the same suffix but no exact entry can reach the regex. Pair those two probes to demonstrate the distinction.

How could an existing index file fail to produce its own contents?

The index module can start an internal redirect to its selected filename. A new location search for that URI may pick a regex that returns another body. Matching the original and final URIs in the log can show that the file choice was made and that a later handler controlled the response.

What does a file test prove before an Nginx reload?

It checks the candidate parse and tries some references using that invocation. It does not establish that the running master accepted the candidate, which location a logged request used, or whether a worker can serve the expected file under its runtime conditions. Test activation and controlled requests for those questions.

When would a custom error page still return 404?

An ordinary error_page rule can use a different internal URI for the body while preserving the original 404 status. This is helpful for readers who get an understandable page and tools that still need a genuine missing result. Explicit status changes and some subsequent processing can change that result, so verify both status and body.

Quick quiz

  1. The wildcard site and an exact workshop name are eligible on the same listener. Which wins for a matching workshop hostname?

    1. The exact name
    2. The wildcard whenever it appears earlier
    3. The default whenever it appears first
    Check the first answer

    A. Exact names take precedence over wildcard names. The default is used for requests without a suitable site match, subject to how Nginx processes the request.

  2. Which output most clearly identifies the internal index selection in this lab?

    1. A redirect status shown before the notes URI
    2. A log line showing the notes folder in the original request and the index filename as the final URI
    3. An unfamiliar port number in the Host header
    Check the second answer

    B. Comparing the two URI fields shows an internal processing step. The successful response and absence of a redirect header provide corroboration that the client was not instructed to change the URL.

  3. What happens when the selected longest prefix is marked to skip regex and the same path also matches a text expression?

    1. The regex handler always wins
    2. Both handlers send a body
    3. For this flat configuration, selection stays with the prefix
    Check the third answer

    C. The prefix modifier bypasses regex search for that match. The assets file's contents confirm the result in the controlled exercise.

Outer context

Follow the service entry and included files. Check whether the directive lives in main, events, HTTP, server or location scope.

Endpoint then hostname

Group server candidates by address and port. Match the name and identify the explicit default for unknown hosts.

Exact, prefix and regex

In a flat set of ordinary locations, trace exact match, longest prefix, optional regex search and the remembered prefix.

Internal URI and external location

Inspect original and final URIs for an internal redirect. An external redirect supplies a status and a client-visible Location header.

Primary references