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

Chapter 8: Configuring Nginx and Apache

AWS Cloud

Practice Questions and Lab Exercises

Use a disposable practice environment. Compare a valid baseline and an intentional bad candidate, then fix or restore it and verify the response.

  1. Trace a request from address and port through hostname, path and response handler.
  2. Find the actual entry file and included site on a practice server. Identify any enablement link and its target.
  3. Explain how each engine selects the fallback for the relevant listener. Verify the parsed order or explicit default.
  4. Move a document root in a disposable fixture. Test the selected public file, required directory policy and an intentional denial.
  5. Use a private loopback port to compare a site declaration with and without a live listener.
  6. Test two named sites and an unmatched authority on the same listener using a local address override.
  7. Use the capstone to review a candidate, verify an accepted route change and roll back a valid but incorrect proxy target.

Quick Revision

  • Identify the listener, selected name and relevant route. That route can serve a file, redirect or forward a request.
  • Trace the actual include chain. Keep private backups outside all active patterns.
  • Compare the candidate with its actual service settings. Use the supported activation method and check the resulting named request.
  • A document-root change needs the policy effective at the new physical path. Inspect applicable filesystem and host policy.
  • A local listener, remote reachability and application authorization need separate evidence.
  • Verify specific status, body, headers and independent controls. If acceptance fails, restore the known compatible version and repeat the same checks.

Got it? Port, site, folder, file – these four questions, plus the backup-test-reload workflow. Now let's move on and give the Amul-style dairy's site a real domain.

Follow-up routing exercises

  1. Sketch a private HTTP backend and its gateway. Verify which path the backend receives.
  2. Classify a client-routed page, a static asset and an API path. Observe separate status, media type and body.
  3. Design a request-rate comparison on a disposable endpoint. Measure accepted, delayed and rejected outcomes for the actual policy.
  4. Use an allowed route and safe denied fixture to verify a scoped policy before and after a change.
Inventory request through NginxRequest to dairy.testNginx chooses routeInventory upstreamJSON response
The inventory branch of the lab. Static guide requests stay in the gateway’s local file route.

Test response headers on successful and failed requests

  1. Pick the applicable response policy and the expected service that owns it.
  2. Check the received headers on a working route and one intentional error. Compare gateway and application responses when both can emit the field.
  3. Review scope and inheritance, then verify the change without duplicating conflicting directives.

Key terms

  • server_name: The host names a server block answers to.
  • listen: The port (and IP) a block binds to.
  • default_server selects the fallback for the particular Nginx address and port.
  • Options -Indexes: The Apache setting that turns off directory listing.
  • semanage fcontext manages persistent path-to-context rules. Label application is separate.
  • limit_req: nginx request rate limiting.

Mini case study

Suppose we are a junior cloud engineer at a Bengaluru e-commerce startup (sample data). The team runs a PHP admin, a Node.js storefront API and a Python report job on two EC2 instances. Using this chapter, you write a one-page runbook: which service listens where, how to test and reload each one, which logs to read, and which endpoints are public, private or reachable through the approved operator access path. New team members can then fix most problems on their own.

Turn a small deployment ticket into testable work

The dairy has published a short guide for customers and a small inventory endpoint used by a workshop page. Another team publishes its schedule on the same host. The dairy asks you to restore an old guide link without moving the current document, exposing staff notes or changing the schedule. During review someone also proposes a new upstream port. Your job is to distinguish a working release from a syntactically valid regression. The exercise gives you one private gateway, one local application, two named sites and a few marker files. You will read the evidence, try a limited positive change, reject a later proposal and verify its rollback.

Begin by translating the ticket into precise behavior. A normal request to the dairy guide should return a particular successful body. An earlier URL should become a temporary redirect to that guide and keep an identifying query value. The inventory route should continue to return a known JSON reply from the private program. An attempt to get the staff fixture should be denied. An intentionally missing static filename should stay missing. The schedule marker should be unchanged, and a request to an unknown host should pick a separate fallback. The ticket is complete only if those results work together through the observed listener.

Keep the local scope explicit. All data is synthetic. Two regular-user processes bind to the local address that points back to your own machine. Neither the public cloud route nor any system service participates. The listener port, path and addresses are local testing values. An application with authentication and real data requires its approved network and access design. Learn the method with the provided fixture first. If you do not have the runtime prerequisites, work through the prediction and reading exercises before trying to replace any command with a service outside the lab.

Know the earlier lessons this practice draws from. The configuration discovery lesson explains why a candidate file only matters when the actual main file selects it. The virtual host lesson explains what changes when a different name is sent to the same listener. The safe-change lesson separates parser validation from service activation and response acceptance. The diagnosis lesson compares gateway evidence with a direct origin response. Combine those checks instead of copying a change workflow by name.

Predict the routing and test the negative paths

Draw two connection arrows. First curl uses the URL name and the frontend port. For this controlled test it resolves the name to loopback. Nginx accepts the connection and chooses dairy, schedule or fallback based on that name. For a static guide the chosen route maps a local file. For the inventory route it becomes a reverse proxy, a program making a distinct request to a service on behalf of the client. The downstream URL is different on purpose. Nginx forwards the path to the actual inventory handler, and the Python service writes a trace record. Observe the address and port separately at each leg.

The fallback serves a 404 with a marker that identifies an unmatched authority. The dairy serves a 404 for a missing file under its own site instead. Those two messages can differ even with the same numeric status. A special staff path produces an intentional 403 for a harmless local file. That reply means the fixture's path policy worked and should not be corrected. Model success and failure in the same worksheet. A success-only test would miss unwanted public access, a renamed route being hidden by a generic fallback, or an unrelated default responding in place of the named site.

Use the table below before reading the setup. Predict status and marker for the original, accepted and rolled-back observations. Keep exact named routes and query values. An error expected from one test case is a useful result. Put a separate mark beside an unintended failure such as the broken inventory route. A permanent error in the fixture should not make you open network rules or restart any unrelated work. Keep each hypothesis scoped to the local process, source file and selected response path you are learning about.

Acceptance sheet for the workshop dairy site and its neighbor
ProbeBaselineAfter accepted redirectDuring wrong port proposalAfter recovery
Dairy guide200 and guide markerSame guideSame guideSame guide
Old guide link404302 and exact destinationSame redirectSame redirect
Dairy inventory200 and JSONSame JSON502200 and JSON
Staff fixture403403403403
Absent asset404404404404
Schedule website200 and independent markerSame markerSame markerSame marker
Unknown host404 and fallback markerSame fallbackSame fallbackSame fallback

The last column deliberately keeps the redirect that already passed acceptance. An operator should restore the latest known good state relevant to the rejected proposal. The earliest saved input is also useful history, but restoring all the way to the start would remove the accepted redirect. Label your backups so you know which baseline belongs to which change. A rollback that fixes the inventory yet removes an independently approved guide behavior would fail this whole ticket. Your tests should establish the exact desired combination.

Warm up with short answers that distinguish concepts

Which settings distinguish address, name, local file path and response handler?

An address and TCP port identify the listener. The HTTP authority selects the virtual server among eligible peers. The chosen location or Apache directive set decides whether to use a filesystem path or an application. If the route serves files, the document root, alias and applicable policies influence the result. Index selection addresses a directory request. If the route proxies or redirects, a different response path follows. Draw the actual branch rather than assuming each request becomes a file.

How would you prove a backed-up copy is outside what Nginx parses?

Read the actual include pattern and candidate output from the same command. A backup in a completely separate directory can be absent from every include even with a dot conf suffix. A backup under a broadly included directory can still match with another suffix. Compare saved bytes and record its relationship to any enabled link. Protect the copy so other site files cannot read or modify it.

What does a successful origin request leave untested?

It verifies a chosen route and response from that origin under the test settings. It does not probe a public HTTPS edge, a route through the intended load balancer or an ordinary DNS resolver. It may bypass a proxy cache or preserve the host differently from an ordinary visitor. Compare both scopes if those layers exist in the deployment. For this lab each test is local by design.

Before the lab, write your own list of likely symptoms. If the named guide fails as a static file while inventory works, the application port is unlikely to be your first question. If the schedule also fails to connect, the shared listener deserves attention. If a healthy direct origin and failing proxy differ by port, compare the gateway's configured destination with the actual listener. Stating the useful next check for each case is part of the practice. A decision can be correct even without memorizing the exact command name when it accurately identifies the required evidence.

Build the private site and its small inventory origin

Use Bash, Python 3, curl and Nginx in a disposable practice shell under a regular account. You need a normal Nginx HTTP proxy build and two usable loopback ports. This exercise uses ports 18899 and 18900 for the two listeners and 18901 as the deliberately unbound target. The availability check below does not reserve them permanently. If a process owns one, leave it alone and choose different unused values, editing all exact references consistently. The cleanup function runs in this shell when it exits and removes only its own children and temporary files. Continue through each block in order.

if [ "$(id -u)" -eq 0 ]; then
  printf 'Use a regular practice account.\n' >&2
  exit 1
fi
nginx_bin=$(command -v nginx) || exit 1
python3 - <<'PY'
import socket
for port in (18899, 18900, 18901):
    try:
        with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as candidate:
            candidate.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            candidate.bind(("127.0.0.1", port))
    except OSError as err:
        raise SystemExit(f"Port {port} is unavailable: {err}")
PY
test "$?" -eq 0 || exit 1
cap_lab=$(mktemp -d /tmp/rb-config-capstone.XXXXXX) || exit 1
ng_pid=
app_pid=
chapter_cleanup() {
  if [ -n "$ng_pid" ] && kill -0 "$ng_pid" 2>/dev/null; then
    kill -QUIT "$ng_pid"
    wait "$ng_pid" 2>/dev/null || :
  fi
  if [ -n "$app_pid" ] && kill -0 "$app_pid" 2>/dev/null; then
    kill "$app_pid"
    wait "$app_pid" 2>/dev/null || :
  fi
  case "$cap_lab" in
    /tmp/rb-config-capstone.??????) rm -r -- "$cap_lab" ;;
  esac
}
trap chapter_cleanup EXIT
mkdir -p "$cap_lab/public/staff" "$cap_lab/sites" "$cap_lab/saved"
printf 'dairy-public-guide\n' > "$cap_lab/public/guide.txt"
printf 'reserved-synthetic-note\n' > "$cap_lab/public/staff/notice.txt"

The setup gives you two actual files and several paths with no file. The public marker gives a body that can be compared for every stage. The reserved note contains synthetic text and is intentionally denied by the config. The fact that this file exists lets you distinguish denial from absence. The site files, saved backups, logs and temporary runtime paths are all inside the generated scope. No credentials or personal data are needed. Response logs record a chosen safe trace label to make the two hops visible.

Start the private origin. It returns a short JSON object on the path the gateway should call. An HTTP 404 is its independent response to a different route. A test request verifies the actual endpoint and content before the Nginx process is started. The JSON media type tells a client it received structured data rather than an earlier HTML page. The trace line shows arrivals at the target and will later let you differentiate an origin request from a gateway failure before forwarding.

cat > "$cap_lab/inventory.py" <<'PY'
from http.server import BaseHTTPRequestHandler, HTTPServer
import json

class Inventory(BaseHTTPRequestHandler):
    def do_GET(self):
        if self.path != "/inventory":
            self.send_error(404)
            return
        trace = self.headers.get("X-Lab-Trace", "-")
        print(f"inventory request trace={trace}", flush=True)
        body = (json.dumps({"boxes": 7, "state": "ready"}) + "\n").encode("utf-8")
        self.send_response(200)
        self.send_header("Content-Type", "application/json")
        self.send_header("Content-Length", str(len(body)))
        self.end_headers()
        self.wfile.write(body)

    def log_message(self, fmt, *args):
        return

with HTTPServer(("127.0.0.1", 18900), Inventory) as listener:
    listener.serve_forever()
PY
python3 "$cap_lab/inventory.py" > "$cap_lab/inventory.log" 2>&1 &
app_pid=$!
app_ready=''
for attempt in 1 2 3 4 5 6 7 8 9 10; do
  if ! kill -0 "$app_pid" 2>/dev/null; then break; fi
  app_ready=$(curl --noproxy '*' --max-time 1 -fsS -H 'X-Lab-Trace: direct-origin' \
    http://127.0.0.1:18900/inventory 2>/dev/null) || :
  if [ "$app_ready" = '{"boxes": 7, "state": "ready"}' ]; then break; fi
  sleep 0.2
done
if ! kill -0 "$app_pid" 2>/dev/null || [ "$app_ready" != '{"boxes": 7, "state": "ready"}' ]; then
  cat "$cap_lab/inventory.log" >&2
  exit 1
fi
printf '%s\n' "$app_ready"

The Nginx entry includes only the site files. An explicit fallback and independent neighbor live in that main entry for the capstone. The dairy config works within its own named block. The exact inventory route forwards to the Python path. The staff prefix denies requests, and the common file policy returns a missing status for an absent path. A staged copy of the config will later add only the retirement redirect. At this point the old guide URL has no file or redirect. Read the entry and config before starting the private process.

cat > "$cap_lab/nginx.conf" <<'NGINX'
worker_processes 1;
pid nginx.pid;
error_log error.log notice;
events { worker_connections 32; }
http {
    default_type text/plain;
    client_body_temp_path body;
    proxy_temp_path proxy;
    fastcgi_temp_path fastcgi;
    uwsgi_temp_path uwsgi;
    scgi_temp_path scgi;
    log_format cap 'host=$server_name uri=$uri status=$status upstream=$upstream_addr trace=$http_x_lab_trace';
    access_log access.log cap;
    server {
        listen 127.0.0.1:18899 default_server;
        server_name fallback.test;
        return 404 "unknown-site\n";
    }
    server {
        listen 127.0.0.1:18899;
        server_name schedule.test;
        return 200 "schedule-still-open\n";
    }
    include sites/*.conf;
}
NGINX
cat > "$cap_lab/sites/dairy.conf" <<'NGINX'
server {
    listen 127.0.0.1:18899;
    server_name dairy.test;
    root public;
    location /staff/ { deny all; }
    location = /api/inventory {
        proxy_pass http://127.0.0.1:18900/inventory;
    }
    location / { try_files $uri =404; }
}
NGINX
cfg() {
  "$nginx_bin" -e stderr -p "$cap_lab/" -c "$cap_lab/nginx.conf" "$@"
}
cfg -t || exit 1
cfg -T > "$cap_lab/parsed.txt" || exit 1
grep -E '^# configuration file|server_name|proxy_pass ' "$cap_lab/parsed.txt"
"$nginx_bin" -e stderr -p "$cap_lab/" -c "$cap_lab/nginx.conf" -g 'daemon off;' &
ng_pid=$!
for attempt in 1 2 3 4 5 6 7 8 9 10; do
  if [ -s "$cap_lab/nginx.pid" ]; then break; fi
  if ! kill -0 "$ng_pid" 2>/dev/null; then break; fi
  sleep 0.2
done
if ! kill -0 "$ng_pid" 2>/dev/null ||
   [ ! -s "$cap_lab/nginx.pid" ] ||
   [ "$(tr -d '[:space:]' < "$cap_lab/nginx.pid")" != "$ng_pid" ]; then
  printf 'The private Nginx listener failed. Check the local existing port and log.\n' >&2
  if [ -r "$cap_lab/error.log" ]; then tail -n 10 "$cap_lab/error.log" >&2; fi
  exit 1
fi

It is important that the parser view and child startup both use the same exact entry and prefix. The process identifier check proves that the child your shell launched owns the PID file for this fixture. If a different process already held the socket, stop and handle the local setup problem. No assumptions about the service's product header or browser output replace this ownership check. In a real deployment the program and control workflow are the ones discovered from the actual service, not the isolated child settings shown here.

Record the full original behavior before changing it

The main verification helper gives each route a specific host, status and optional expected body. It captures HTTP errors as data for the exercise. All requests keep the same connection destination while supplying the intended name. Print only small synthetic markers so a reader can see which route responded. The most important cases include a positive file, an API body and two distinct denials. For the staff and missing-path responses, check their numeric status and consult the relevant logs. A different client path sent to the same server can have the same status for another reason.

observe() {
  local host=$1 path=$2 trace=$3
  curl --noproxy '*' --max-time 5 -sS --resolve "$host:18899:127.0.0.1" \
    -H "X-Lab-Trace: $trace" -D "$cap_lab/result.headers" \
    -o "$cap_lab/result.body" -w '%{http_code}' "http://$host:18899$path"
}
expect_route() {
  local host=$1 path=$2 trace=$3 expected=$4 marker=${5-} status
  status=$(observe "$host" "$path" "$trace") || return 1
  printf '%s %s HTTP %s\n' "$host" "$path" "$status"
  [ "$status" = "$expected" ] || return 1
  if [ -n "$marker" ]; then [ "$(cat "$cap_lab/result.body")" = "$marker" ]; fi
}
controls() {
  expect_route dairy.test /guide.txt guide-check 200 dairy-public-guide &&
  expect_route dairy.test /staff/notice.txt staff-denied 403 &&
  expect_route dairy.test /missing.txt missing-asset 404 &&
  expect_route schedule.test / neighbor-check 200 schedule-still-open &&
  expect_route mismatch.test / fallback-check 404 unknown-site
}
inventory_check() {
  expect_route dairy.test /api/inventory "$1" 200 '{"boxes": 7, "state": "ready"}' &&
    grep -Eiq '^Content-Type: application/json' "$cap_lab/result.headers"
}
controls || exit 1
inventory_check inventory-before || exit 1
expect_route dairy.test '/old-guide?from=fair' before-redirect 404 || exit 1
test -f "$cap_lab/public/staff/notice.txt" || exit 1
cp -p -- "$cap_lab/sites/dairy.conf" "$cap_lab/saved/dairy-original.conf" || exit 1
cmp "$cap_lab/sites/dairy.conf" "$cap_lab/saved/dairy-original.conf" || exit 1

If any baseline expectation fails, diagnose it before moving on. For example, the direct inventory service may initialize but your named gateway request can still select an incorrect site. The header and exact JSON check establish that the appropriate path received an application response. Comparing the saved bytes before editing establishes the restore point. The copy is outside the actual include and uses a different name. The original stage must report missing for the requested retired guide route. That expected failure is what the next approved change should alter.

Add one redirect and verify the accepted state

Write the candidate outside the selected includes and promote it only after inspecting the one intended change. Below, a Python helper identifies the original catch-all location exactly once and inserts a distinct exact-match redirect before it. The original generic file rule stays available. The destination is a fixed lab name and URL path, with the existing query appended when present. An unrecognized authority cannot acquire this redirect because the rule lives under the intended dairy hostname. A temporary status makes the exercise easier to repeat without relying on whether an earlier client remembers a permanent redirect.

active="$cap_lab/sites/dairy.conf"
original="$cap_lab/saved/dairy-original.conf"
approved="$cap_lab/saved/dairy-approved.conf"
bad="$cap_lab/saved/dairy-proposal.conf"
python3 - "$original" "$approved" <<'PY'
from pathlib import Path
import sys

source = Path(sys.argv[1]).read_text()
anchor = '    location / { try_files $uri =404; }'
addition = (
    '    location = /old-guide { '
    'return 302 http://dairy.test:18899/guide.txt$is_args$args; }\n'
)
if source.count(anchor) != 1:
    raise SystemExit("Expected one original catch-all route")
Path(sys.argv[2]).write_text(source.replace(anchor, addition + anchor))
PY
test "$?" -eq 0 || exit 1
review_diff() {
  local rc
  if diff -u "$1" "$2"; then
    printf 'Expected a change between candidates.\n' >&2
    return 1
  else
    rc=$?
    [ "$rc" -eq 1 ]
  fi
}
install_candidate() {
  local source=$1 temp
  temp=$(mktemp "$cap_lab/sites/.dairy.XXXXXX") || return 1
  if cp -p -- "$source" "$temp" && mv -f -- "$temp" "$active"; then return 0; fi
  rm -f -- "$temp"
  return 1
}
cmp "$original" "$active" || exit 1
review_diff "$original" "$approved" || exit 1
install_candidate "$approved" || exit 1
cfg -t || exit 1
kill -HUP "$ng_pid" || exit 1

The checked candidate copy works as a record of the proposed source. Label it approved only after completing the next stage. The script copies it into a same-directory temporary path whose name does not match the include, then replaces the selected site file with the complete bytes. This is a single-writer teaching fixture. A real configuration manager may need its own concurrency control and ownership rules. Once the parser reports success, the known child receives the request to apply it. The signal is not treated as proof of actual response behavior.

wait_status() {
  local path=$1 expected=$2 code
  for attempt in 1 2 3 4 5 6 7 8 9 10; do
    code=$(observe dairy.test "$path" transition-check) || return 1
    if [ "$code" = "$expected" ]; then return 0; fi
    sleep 0.2
  done
  printf 'Expected HTTP %s for %s, most recent result %s.\n' "$expected" "$path" "$code" >&2
  return 1
}
check_redirect() {
  expect_route dairy.test '/old-guide?from=fair' redirect-check 302 &&
    tr -d '\015' < "$cap_lab/result.headers" |
      grep -Fxi 'Location: http://dairy.test:18899/guide.txt?from=fair'
}
wait_status '/old-guide?from=fair' 302 || exit 1
check_redirect || exit 1
expect_route dairy.test '/guide.txt?from=fair' redirect-target 200 dairy-public-guide || exit 1
controls || exit 1
inventory_check inventory-approved || exit 1
cmp "$approved" "$active" || exit 1

Inspect the first response's status and exact Location with its query. The next line verifies the actual destination. The first part provides the navigation instruction. The second proves the document it names still works. The accepted state includes the guide, inventory JSON, staff denial, missing path, schedule and fallback. This is the version to preserve for recovering from the next attempted change. If a first probe sees the previous 404 during the private worker transition, the bounded loop grants a brief chance for acceptance. Investigate before proceeding if the desired response does not appear.

Reject a valid but broken proxy candidate and restore the last good version

The next proposal changes the upstream port from the actual private inventory listener to the selected unused endpoint. This is a known failure you can reproduce without stopping the real fixture origin. The configuration remains valid text. Run the candidate's syntax test, apply it only inside this isolated lab, and check the resulting behavior. Wait until the gateway returns 502 to distinguish a rejected probe from a transitional request using older workers. Then make a fresh attempt with the failure trace marker. The good upstream should have no corresponding record, while the gateway logs show its wrong address. That exact history establishes that the relevant application did not receive this request.

python3 - "$approved" "$bad" <<'PY'
from pathlib import Path
import sys

source = Path(sys.argv[1]).read_text()
present = "proxy_pass http://127.0.0.1:18900/inventory;"
proposed = "proxy_pass http://127.0.0.1:18901/inventory;"
if source.count(present) != 1:
    raise SystemExit("Expected a single inventory proxy line")
Path(sys.argv[2]).write_text(source.replace(present, proposed))
PY
test "$?" -eq 0 || exit 1
cmp "$approved" "$active" || exit 1
review_diff "$approved" "$bad" || exit 1
install_candidate "$bad" || exit 1
cfg -t || exit 1
kill -HUP "$ng_pid" || exit 1
wait_status /api/inventory 502 || exit 1
expect_route dairy.test /api/inventory inventory-failed 502 || exit 1
grep -F 'uri=/api/inventory status=502 upstream=127.0.0.1:18901 trace=inventory-failed' \
  "$cap_lab/access.log" || exit 1
if grep -Fq 'trace=inventory-failed' "$cap_lab/inventory.log"; then
  printf 'The origin unexpectedly logged the rejected request.\n' >&2
  exit 1
fi
check_redirect || exit 1
controls || exit 1

In an actual release you might use a staged private canary instead of applying a known bad candidate in place. Here the bad proposal acts as a verified contrast. The same frontend loopback listener responds, and the selected dairy host and guide still work. The failure affects the one proxied route. A successful direct request to the actual origin helps confirm that the application remains healthy on its known port. A later inspection of an unrelated application's logs would not explain the observations. The relevant comparison is between the configured endpoint and the actual working origin.

Restore the latest known good config, which is the accepted redirect state. Compare the installed bytes with that file, then test and reapply the correct route. Make the same named application request with a new distinct label, and check the origin log for that label. Reconfirm that the guide redirect and its intended exact destination were preserved. If you restore the earliest original instead, the inventory may look fixed while the completed guide task regresses. Your verification should catch that difference. The recovery is complete when actual output proves both the unaffected neighbor and the desired combination for the changed site.

install_candidate "$approved" || exit 1
cmp "$approved" "$active" || exit 1
cfg -t || exit 1
kill -HUP "$ng_pid" || exit 1
wait_status /api/inventory 200 || exit 1
inventory_check inventory-restored || exit 1
grep -F 'trace=inventory-restored' "$cap_lab/inventory.log" || exit 1
check_redirect || exit 1
expect_route dairy.test '/guide.txt?from=fair' restored-target 200 dairy-public-guide || exit 1
controls || exit 1
tail -n 12 "$cap_lab/access.log"

Keep the important log evidence before removing the fixture. Save at least one original response, one accepted redirect, the failed attempt and the restored inventory receipt. Include the selected site and exact endpoint at each stage in written work. Without that context, the access log can look like a collection of disconnected statuses. Stop both child processes and remove their scratch area after completing your report. If an earlier step failed, the same cleanup route is available, and leaving the practice shell runs its registered handler.

chapter_cleanup
trap - EXIT
test ! -e "$cap_lab" && printf 'Chapter 8 capstone lab removed.\n'

Try four additional exercises with worked explanations

Differentiate a local redirect from a direct origin response

An operator copies the Inventory URL from the gateway log and gets a 404 from the Python listener. They ran a direct request to the public path because that was the route users called. Some web services deliberately use different paths at the two hops. In this capstone the public path has an application prefix, while the private application listens to its own inventory resource. Predict each direct response before looking at the proof. The test below can be run before cleanup after the final rollback. It is read-only against the two private services. Test the two origin paths with distinct trace labels and compare them to the named external input you already verified.

direct_status=$(curl --noproxy '*' --max-time 5 -sS -o "$cap_lab/audit-origin.body" \
  -w '%{http_code}' http://127.0.0.1:18900/api/inventory) || exit 1
printf 'Direct app-prefixed path HTTP %s\n' "$direct_status"
test "$direct_status" = 404 || exit 1
direct_status=$(curl --noproxy '*' --max-time 5 -sS -D "$cap_lab/audit-origin.headers" \
  -H 'X-Lab-Trace: correct-origin-path' -o "$cap_lab/audit-origin.body" \
  -w '%{http_code}' http://127.0.0.1:18900/inventory) || exit 1
printf 'Direct inventory path HTTP %s\n' "$direct_status"
test "$direct_status" = 200 || exit 1
grep -F 'trace=correct-origin-path' "$cap_lab/inventory.log" || exit 1
python3 - "$cap_lab/audit-origin.body" <<'PY'
import json
from pathlib import Path
import sys

data = json.loads(Path(sys.argv[1]).read_text())
assert data["boxes"] == 7 and data["state"] == "ready"
print("Verified the two expected inventory fields.")
PY

The first direct request should return 404. The second returns the expected inventory object, and the app logs its trace. This checks actual decoded values, so an equivalent object with its fields reordered remains valid for the field check. The earlier compact string expectation was acceptable because the fixture produced a completely known body. In a production contract, decide which fields and types matter and test them as data. A media type identifies a format, but a successful parse and expected values supply more evidence. The public gateway can preserve that response while mapping an incoming prefix to a different private path.

Examine two hostnames with identical paths and a conflicting canonical rule

A designer proposes a second alias for dairy. Their candidate would redirect any unmatched host to the new guide. Your acceptance sheet should object to that change even if customers who use the exact expected address see a working guide. The independent fallback is supposed to identify a route that did not select a known host. A rule that sends every unmatched name into a successful page makes it harder to detect bad inputs. Write separate outputs for dairy, its known alternate if approved, schedule and mismatch. Confirm the initial request's status and expected authority before verifying the destination body. A named redirect and an unmatched default are distinct policies.

Now imagine an ordinary HTTPS deployment where the alternate is an existing public name. The team adds a configured redirect but forgets to add that name to the appropriate certificate coverage. Explain why the user might never receive the good HTTP redirect. The encrypted setup comes first. Check the proper TLS termination point and expected hostname for the initial and final requests. If the latest accepted source includes the new alternate but public DNS and certificate state are managed elsewhere, those dependencies must be included in the real rollout plan. Your local example verifies plain HTTP and does not claim to test that extra chain.

Choose logs that can support a useful failure statement

Revisit the failed branch with the two log excerpts in front of you. The gateway's row contains the selected frontend name, route, status and upstream destination. The origin's log has a verified arrival on the intended endpoint before the bad proposal and after restoration. There is no standalone origin line for the bad trace. Write one sentence explaining which comparison turns that absence into useful evidence. The gateway recorded an attempted different endpoint, and your known working trace format shows what a received request on the correct origin would look like. If those controls were absent, the missing row might instead mean you were looking at a different log file, a delayed sink, or a log filter.

In a larger service, trace markers can be generated by infrastructure and passed through more than one hop. Keep the field necessary to link the records. Don't invent private values or move entire request logs into a public report. Add evidence within the approved scope and use synthetic input wherever possible. Ask which component knows the true incoming authority, where proxy attempts are recorded and whether the final log timestamp includes a delayed queue. This practice turns a general instruction to read logs into a focused data request that a site operator can fulfill.

Design a separate verification strategy for a failed rollout before activation

Suppose the second proposal had an unterminated directive instead of a valid wrong port. You would expect the candidate to fail the parser, while the already accepted guide and inventory still answer. Repair the selected on-disk input but avoid implying that a previous runtime regression occurred. Different recovery is needed if a syntax-valid candidate entered service and changed the behavior. In that case you must reapply the right source and verify the active result, as the capstone did. Write a two-row comparison of the actions necessary in each case. Use the already established named request and independent site as controls. Do not skip the runtime verification merely because the parser problem seemed obvious.

Finally decide whether a concurrent update should proceed. If another authorized maintainer changed dairy between your original saved copy and the rejected proposal, restoring your file may remove their work. Check the expected previous input against the current managed version before copying a known source. Coordinate through the service's normal ownership and revision workflow. The capstone compares exact copies because it is designed for one writer. An operational rollback should recover a known compatible state without accidentally reopening access or discarding unrelated accepted changes. Your written comparison should state which version belongs to this proposal and what evidence makes it the correct recovery point.

Turn your observations into a reviewable submission

Start the report with a two-line scope statement. State which two local processes and ports you tested. List the three authority values used to choose dairy, schedule and fallback. Then name the exact origin path and media type used by the inventory route. This gives the reviewer context when you write that the proxy returned 502. A response from the first listener and a refusal from the second socket are different steps in the same request. Say which one provided each observable result.

Next attach a small verification table. Include the route, requested hostname, expected status, returned body or Location marker and relevant log trace. Write expected denial and unexpected failure in different rows. For the staff route, confirm that its harmless file exists and was intentionally blocked. For the absent asset, record that its file did not exist. For the fallback, record the body that identifies an unrecognized name. Using one known test per state makes these distinctions clear. A generic screenshot of a 404 page cannot show which branch produced that status.

Explain the accepted redirect in two phases. The initial URL had no mapping and returned 404 at the intended site. After the approved file change the exact location sends a 302 containing the fixed local destination. The query label carried in the Location shows a deliberate option was retained. The second request to that destination returns the existing public file. A different path that returns the same 200 status is insufficient if the query dropped or the redirected hostname is wrong. Preserve the first response headers and second response marker in the submission.

Then provide the before and after evidence for the rejected proposal. The parser saw a syntactically possible private address and port. Its successful check says nothing about whether another process listens on that socket. The original upstream remained reachable at the correct port. The 502 and selected address in the gateway log establish what Nginx attempted. The absent arrival at the healthy process is supported by a working baseline trace and a restored one. Absence from a misconfigured or unavailable log alone would be weak evidence, which is why the controls matter.

Add one acceptance check to the report for file identity after a release retry. Treat the saved candidate and on-disk source as separate artifacts. If you repeat a command after an SSH interruption or a failed automation action, first read which source is currently selected and which response the live service shows. The request might have reached another backend or an older worker, and the candidate might already have been copied. Comparing exact bytes and getting a fresh request gives you a place to resume. If the state has changed by another approved operation, resolve that drift with the responsible operator before overwriting it.

Describe a narrower case in which the application moves to another actual port. The plan should start the correct application listener and prove its own readiness before routing ordinary requests to it. A syntax check of the Nginx candidate can pass earlier, when the application is still starting. Separate readiness from candidate eligibility, update the intended route and verify the user-facing body and unaffected paths. Then retire the earlier endpoint according to the approved cutover. For rollback the old port also needs a working receiving application, or changing the route back only restores a name in a config file. This scenario explains why one successful parser run cannot schedule a safe dependency switch by itself.

Use the capstone trace goals to make checks repeatable. After any repeated attempt, distinguish the most recent result from a successful request in the original log. Give the repeat a fresh harmless trace and check the exact status and media type from that attempt. A stored public guide response may be eligible for cache reuse in a real system, while an inventory reply may need a different policy. Confirm the intended normal edge route if one exists, so a private origin test does not get mistaken for a visitor's result. In this practice the simple loopback route and synthetic response make repeats independent of external caches.

Finally describe the rollback. Say which exact version was restored and identify the newer behavior it retained. Record that the correct inventory trace appeared after restoration and that the approved redirect still sends to the right target. Include the stable neighbor and deliberate negative probes. This closes the loop. Removing the temporary fixture at the end is cleanup. It is separate from proving that the accepted end state worked before teardown. Save any results needed for review first.

Choose a follow-up that changes one deployment variable

Swap the serving file while keeping the URL and proxy

Plan a variant where the dairy wants the guide body changed but its old link and inventory remain. Build a second dedicated public release with a different guide marker and keep the existing synthetic staff rule. Determine whether the same file path could be updated by a release artifact or whether a new root should be activated. Choose one method. If you change only the file without touching the config, the gateway can serve new bytes at the same ordinary lookup while the redirect still points at the same route. If you change the root, the selected scope and actual directory must be checked. Use the Nginx document-root exercise for a separate measured switch and restore. Test new guide, old redirect, denied note and API before releasing the candidate.

Sketch the equivalent Apache acceptance criteria

Keep the intended HTTP results but use Apache terminology to draw a candidate. Write which actual Listen endpoint accepts the incoming connection, the matching VirtualHost name, the public DocumentRoot and scope that should be allowed. Identify which supported reverse proxy module and directive could send the API to the intended downstream address. The private port must be reachable from that Apache instance. A local scoped denial and unknown default should remain. Explain how Apache's parsed host ordering establishes the default, and check both the forwarding and any returned backend redirect if that behavior is in scope. Earlier lessons about Apache sections and about its root rollback include independently tested local processes. This follow-up checks your design rather than assuming the Nginx syntax can be pasted into Apache.

Check headers for successes and errors

Suppose the deployment needs a response header with a particular policy only on the public document and a known error response. Decide which service should own it. Then choose a narrow private candidate and inspect both the positive GET and deliberate error GET. A header that appears on the homepage may be omitted on an error or under a location with its own settings. The applicable Nginx version has documented inheritance and status controls. A reverse proxy or application can also supply a duplicate. Read every received instance of the header and agree on one policy owner. If you compare a direct origin and ordinary route, explain which boundary controls the user-visible answer. This is a stronger test than assuming a single gateway directive covers all sites.

Verify policy without depending on a public source address

Suppose the reviewer asks whether the site's reserved content is public. Keep the exercise in the isolated listener and use a harmless existing file marker. Compare a successful allowed route with the expected denial. If you need to check a real environment, use only its authorized roles and network paths. An access result from one machine on a private route cannot prove the policy on a public listener or authenticated front door. Read the rule and confirm the inputs that select it. A client IP address may be a useful network control, but it is not a substitute for the correct application identity. The capstone's simple refusal shows scope and status without involving anyone else's data.

Review questions, quiz and revision cards

Why was the first missing old-guide route a useful expected 404?

It establishes the original condition that the accepted change should alter, using the intended listener and name. Compare it with the later 302 and correct destination body. The baseline also helps distinguish whether the route already existed before the edit.

Why can the wrong upstream port pass a syntax test?

It is a valid address written in syntactically acceptable configuration. The checklist has to prove application reachability and correct implementation behavior separately. The gateway request actually attempts that connection and gives evidence about the chosen port.

What does it mean when the log shows the intended origin port after recovery?

The gateway chose that port for the recorded attempt. Pair this with its successful status and JSON body and the matching application trace. An address string alone does not prove an upstream supplied the representation.

Why restore the latest approved candidate instead of the earliest backup?

The latest approved source includes the verified redirect and working inventory. Reverting farther would lose an unrelated completed change. Test the specific restored source and verify both the redirect and the API after activation.

Does localhost prove the ordinary cloud setup works?

It proves the path scoped to the local fixture and designated listeners. Real DNS, TLS, network controls and edge routing are separate concerns. State the boundary so your verified result is useful and accurate.

Quick quiz

  1. After rollback the API works, but the old guide route is 404 again. Which likely explanation should you check?

    1. The earliest saved file was restored instead of the later approved file
    2. The stable schedule marker needed a new body
    3. The inventory program must change its JSON formatting
    Check the first answer

    A. The earliest version used the correct proxy but lacked the accepted redirect. Confirm which file was restored and repeat both probes.

  2. Two requests get 404. One has the unknown-site marker, the other is a missing file on dairy. Which evidence distinguishes them?

    1. The word error shown by the browser alone
    2. The request hostname, selected site in the log and response marker
    3. The number printed on the EC2 instance label
    Check the second answer

    B. A shared status can describe distinct routing decisions. Match input and serving context before choosing a fix.

  3. The proxy proposal gives 502 while the known origin continues to return JSON. The logged attempted port differs from the known origin socket. What is the targeted repair?

    1. Restart the unrelated schedule service
    2. Broaden remote network access
    3. Use the verified correct inventory destination and repeat the original route plus independent controls
    Check the third answer

    C. The incorrect address is observed, and the previous target is reachable. Restore the known config and verify actual behavior before calling it recovered.

Make requirements observable

Record expected status, body or headers for intended successes, intentional failures and neighboring requests.

Two separate connections

The gateway accepts a named request and can make another connection to its upstream. Observe both scopes independently.

Latest approved baseline

Save each verified state. Recover the prior version relevant to the rejected change and confirm all accepted behavior.

Evidence before teardown

Save exact request paths, markers and safe log excerpts. Then stop the lab children and remove the scratch root.

Primary references