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

Chapter 7: Static Website Hosting (3 OSes × 2 Web Servers)

AWS Cloud

7.6 Combination 1 — Amazon Linux 2023 + Nginx

Come on, the first combination – Amazon Linux 2023 and Nginx. Use the assigned practice instance for these commands. The other combinations follow a similar sequence with different packages, configuration paths and service names.

Start by identifying the assigned host and checking the package and listener state. The expanded procedure below shows the site file, preflight validation, and activation for this lab.

cat /etc/os-release
sudo dnf info nginx
sudo ss -ltnp 'sport = :80'

Open http://<PUBLIC_IP> in your browser.

Why server_name = public IP here?

Amazon Linux and CentOS already have a default server { server_name _; } block inside /etc/nginx/nginx.conf that serves /usr/share/nginx/html. Giving our block the exact public IP (or a domain like mysite.example.com) makes Nginx pick our block when the browser asks for that host. If you later attach an Elastic IP or a domain, update server_name and reload. Quick method instead: simply copy your files into /usr/share/nginx/html/ — no config needed.

Ravindra Bagale's Tip

A request to the raw address can select the default site because it sends that address as the host. When using a stable hostname, keep the same server_name and test its new DNS destination after any address change. If the configured name itself changes, validate the configuration before reloading the active service.

Lab

Chala, practice instance var khalcha pahila lab kara. Assigned hostname vapra. Homepage cha status ani olakhichi line bagha. Naslela path request kara ani custom page sobat 404 status tapasa. Mag tya site chya access log madhe ti request shodha.

Host a shop notice on Amazon Linux 2023 with Nginx

A neighbourhood dairy needs a simple web notice for its order collection hours. An employee prepares the notice with a stylesheet and a separate page for today's rates, then sends a link to the manager for approval. The manager gets an Nginx welcome page. The employee has copied the files correctly onto the instance, but the request has selected the packaged site instead of the one for the dairy. This combination teaches the missing connection between a published directory and a request for a particular host.

We will give that connection a name and a test. A request for the shop should read the release from its approved folder, a request for the stylesheet should return CSS, and a request for a page the shop never published should send a helpful error page with HTTP status 404. We will distinguish each of those conditions from an Amazon EC2 networking problem. The full machine exercise uses an assigned Amazon Linux 2023 instance. A shorter loopback exercise later works wherever you already have the Nginx binary and Python, and leaves the system service alone.

Keep a note with the AWS account and Region, the instance name and ID, the operating system, and the practice hostname for your exercise. Beyond the instance identifier you only need ordinary public sample pages. A course URL, a screenshot of the AWS console, or a server's appearance in a previous shell session can become stale. Write down the specific machine from which you ran your commands and the exact URL you later verified. Use this record to connect the release to a piece of evidence someone else can reproduce.

Follow one request from the browser to a file

Suppose the assigned training name is mauli-orders.example.test. The suffix in the example is reserved for testing, so this name needs a local override for the exercise. A web request has a destination address, a port, and a name from the URL. The address tells the client which machine to connect to, and port 80 is the usual destination for HTTP. The name tells Nginx which site's rules to use when several names share that listener. The path tells the selected site which resource the client wants. These details can differ independently.

Information that travels with the shop homepage request
DecisionPractice valueResult
Connect to a listenerLocal address, port 80The HTTP connection reaches the intended process on this instance.
Select a sitemauli-orders.example.testThe named server block supplies its root and log destinations.
Map a homepage/The site's directory index setting locates its homepage file.
Fetch a dependency/css/style.cssA second HTTP request reads the stylesheet from the same published release.

A browser following a link builds both the connection and the HTTP request from the URL. For this lab, curl can substitute the destination address for one hostname and port with --resolve. The URL still contains the practice name, so curl can send the host information Nginx needs. This is useful before any DNS record exists and leaves DNS and the operating system's hosts file untouched. Accessing only a bare address tests a different host value, even if both requests ultimately reach the same machine.

Nginx selects a group of server blocks by the address and port that accepted the connection, then considers the requested name. If no name matches, the listener has a default. The default may be declared explicitly, or Nginx may use the first appropriate server for that socket. A welcome page with status 200 demonstrates that something responded on the requested path. The shop-specific text and its per-site access log provide stronger evidence about the site selection. Adding a new named block leaves the existing default intentionally in place, so its normal use can continue.

Recognize the instance, package manager, and service

Open the shell on the assigned practice instance and view /etc/os-release. For Amazon Linux 2023 you should see an Amazon Linux name and a version identifier of 2023. A training group may use similar EC2 instance names for Ubuntu and Amazon Linux, so inspect the guest directly. The id command identifies the current login and its groups. You can use this evidence if the shell refuses an administrative step. Use the approved access path and ask the lab owner about the role or account in use if its permissions differ from the course setup.

cat /etc/os-release
id
command -v dnf
sudo dnf info nginx
rpm -q nginx
sudo ss -ltnp 'sport = :80'

Read those results before installation. DNF queries package repositories, while the RPM query reports whether a matching package is already installed on this system. A failure in the repository query may be a repository configuration, network, DNS, or package metadata issue. Record the repository error. A port listing may reveal something listening already, such as an Apache process or another Nginx instance. The listener and its owner matter more than the fact that a command exists on disk. On an occupied or shared machine, confirm the service and its owner before changing configuration.

Amazon Linux 2023 uses DNF as its standard package manager. The yum command remains available as a compatibility path on AL2023, so a successful older yum command tells you very little about which generation you are administering. The packaged Nginx executable and the service unit are separate pieces of evidence. A service unit is systemd's description of the process and its start, stop, and reload behaviour. One image may already ship with a web stack installed while another will need packages from its configured repository.

sudo dnf install nginx
rpm -q nginx
nginx -v
systemctl cat nginx
systemctl is-active nginx
systemctl is-enabled nginx

Only run the install on an assigned disposable instance after confirming the proposed changes. Read DNF's transaction summary and check what package will be installed. nginx -v identifies the binary invoked in your shell. systemctl cat nginx shows the packaged unit and any drop-in overrides visible to systemd. The last two commands report separate states. Active means systemd currently sees the service running. Enabled describes a configured activation relationship, commonly whether the service is set to start via a boot target. A service can run for a short exercise without being enabled. Some unit states also use labels such as static or masked, so read the actual output.

On a fresh AL2023 host, you may start the approved service before publishing a site to see its initial behaviour. In this lesson you can test your candidate configuration first and then start the service if it is inactive. If it is active and managed by the lab, validate and reload it after adding the new site. Enable it at boot only if the lab calls for a reboot test. Keep the before-and-after service state in your notes so cleanup can restore that state on a retained training instance.

Find where Nginx actually reads the new server block

A server block is the group of settings that handles requests for a particular site on a listener. Nginx starts with a main configuration file. An include directive loads text from another file, or loads several matching files from a pattern. The placement of an include determines which kinds of directives can appear in that file. A server block for ordinary HTTP must belong inside the http context. A file placed in a directory that does not participate in that include chain will never become part of the running server's rules.

On the expected AL2023 RPM setup inspect the main configuration and confirm that the http block includes matching files from /etc/nginx/conf.d/. Use the installed service's effective config if the lab image has changed it. The uppercase -T performs a configuration test and prints the expanded configuration, including included files. The lowercase -t tests the configuration without the full dump. Read the expanded output locally on your approved lab machine. It may include hostnames, internal addresses and other operational settings that belong with the administrator.

sudo nginx -t
sudo nginx -T
rpm -ql nginx
systemctl cat nginx

Record three specifics from that inspection. First write down which physical file or pattern will load a new site. Then look for an existing listener at port 80 and identify the blocks that use the name of your practice site. Finally check that MIME type mappings are included at the HTTP level. MIME types are response labels like text/html and text/css that help browsers interpret the body. Getting the shop HTML back proves little about the separate stylesheet. Logging and content-type checks will make those distinctions observable.

Study the test output even when its exit status indicates success. An Nginx duplicate-name warning can indicate one declaration is ignored. A filename that differs from the include pattern will produce no syntax error at all, because the file is never loaded. Two successful runs of nginx -t, one before and one after staging an edit, say that both configurations parsed. They need a request for the intended host to establish that the change did what the employee asked.

Prepare the public release before changing Nginx

In this example, the assigned published directory is /var/www/mauli-orders-lab. Use a new approved location or a directory expressly created for the lesson. The public sample in lesson 7.3 contains index.html, rates.html, 404.html, and css/style.css. Treat those four relative paths as a small release manifest. Inspect the staged tree before installation. The file that arrived in a login home directory is an input to the release, and the document root is the version selected for serving. You can compare both before touching the site's configuration.

Put a distinctive marker in each HTML file. A title in the homepage can say “Mauli collection notice”. The rates page can say “Mauli rates for this training release”. Put “Mauli page unavailable” in the custom error body. Use a different line of CSS for the style check, for example a rule for .collection-hours. These phrases need no real prices or personal details. Make the CSS reference an absolute path within the site, such as /css/style.css, so a custom error view returned to a client asking for a nested URL can find the same stylesheet.

Check file reads and parent directory traversal at the intended root. A typical disposable public sample may use 0755 directories and 0644 files, with the administrator or publisher owning them. The worker processes need to read files and traverse directories. They do not require write access to the public release for this lesson. Administrative success with sudo ls confirms the files exist for that administrator. The actual HTTP request gives evidence about the Nginx worker and its policy. If the instance enforces SELinux or another host policy, verify any context or permission change using that distribution's tools and the lab owner's policy.

ROOT=/var/www/mauli-orders-lab
ls -ld "$ROOT" "$ROOT/css" "$ROOT/index.html" "$ROOT/css/style.css"
namei -l "$ROOT/index.html"
find "$ROOT" -type f -print | sort

A root listing gives the last component's attributes. namei -l traces path components from the start, so it can show a parent directory that the worker cannot traverse. A manifest comparison can expose a nested upload such as mauli-orders-lab/mysite/index.html. In that case the file exists in the wrong location for the configured mapping. Preserve the known-good release tree while you correct placement. A publisher should be able to point to the exact files selected by the current root without guessing from an SSH prompt.

Read the site configuration as a set of decisions

For the training name use a site file called mauli-orders-lab.conf. On the approved image place it in the verified include directory only after reviewing its contents. This sample uses a single IPv4 listener on port 80 and names one site explicitly. The additional IPv6 listener or TLS endpoint needed by a real project has its own routing and test plan. Keep the existing default and other named blocks as they are. Replace the hostname only if the lesson owner assigned a different approved name.

server {
    listen 80;
    server_name mauli-orders.example.test;
    root /var/www/mauli-orders-lab;
    index index.html;

    location / {
        try_files $uri $uri/ =404;
    }

    error_page 404 /404.html;
    location = /404.html {
        internal;
    }

    access_log /var/log/nginx/mauli-orders-lab.access.log;
    error_log /var/log/nginx/mauli-orders-lab.error.log;
}

The outer block links this hostname to the chosen local root. The first location applies to the site's general URL path. try_files checks candidate paths according to the site's mapping. Here Nginx considers an existing file or directory, and the final =404 is the response status when none of the candidates exists. For a directory that qualifies, the index module can find index.html. An existing directory without its expected index can produce a different failure, such as a forbidden directory listing. That difference explains why the training test deliberately asks for a distinct, absent path.

The error_page setting maps the 404 response to the local URI /404.html. Nginx fetches the body through an internal request, and the original missing resource still has a 404 response status. The exact location marked internal permits that internal request. The custom error body therefore needs its own file and a readable path, just like the homepage. A browser shows that body while leaving the missing URL in its address bar. Test both the body marker and status before claiming that the error page works.

Per-site access and error logs help separate requests to this lesson's host from records for another host. The access log records requests handled by the site, including deliberate 404 requests in your check. The error log may show evidence such as an unreadable path or a failure to open a configured resource. An entry for every 404 is unnecessary and depends on the chosen mapping and log settings. Successful status, a content marker, a selected request path and log evidence together make a more useful inspection than a screenshot of the HTML alone.

Install and validate only the assigned configuration

Save the block above first into a new regular file called mauli-orders-lab.conf inside your learner workspace. A plain text editor helps keep quotation marks and file extensions predictable. If you use a shell here document, quoting the delimiter as <<'NGINX' prevents the shell from expanding Nginx's $uri variables while writing the file. Check the saved bytes and learn to tell shell text from a server directive. In particular, a pasted unquoted here document can silently substitute an empty shell variable before the configuration tester gets a look at it.

Choose the correct source file in the shell below. It assumes the approved RPM include path was verified and the destination is new. The shell creates the file in noclobber mode, which makes an existing regular destination cause failure. The early check also refuses a symlink, including a dangling one. Run these commands with the lab manager's approval in an include directory writable only by trusted administrators, with no concurrent configuration changes. If the destination exists, record the collision and ask the owner to identify the existing site rather than continuing.

(
set -eu
candidate="$PWD/mauli-orders-lab.conf"
destination=/etc/nginx/conf.d/mauli-orders-lab.conf
test -f "$candidate"
test ! -L "$candidate"

sudo sh -c '
  set -euC
  if [ -e "$2" ] || [ -L "$2" ]; then
    printf "Existing configuration: %s\n" "$2" >&2
    exit 1
  fi
  umask 022
  cat "$1" > "$2"
' sh "$candidate" "$destination"
sudo nginx -t
)

Review the command output before activating the file. A failed nginx -t stops this stage while the existing process, if there is one, still uses its loaded configuration. Fix the candidate or remove only the new file created in the lesson and rerun the configuration test. Do that promptly. A currently running configuration and the bytes waiting on disk are separate states. A reboot or later reload could otherwise try to read the invalid bytes from disk. For a retained machine record which candidate you changed, the prior accepted state, and the exact validation output.

# Choose the command appropriate to the service state recorded above.
sudo systemctl reload nginx
# If the lab service is inactive instead:
sudo systemctl start nginx

systemctl is-active nginx
sudo ss -ltnp 'sport = :80'
sudo journalctl -u nginx -n 15 --no-pager

Reload asks an active process to adopt the configuration, usually with new worker processes and a graceful handoff to existing ones. On this lab service start is a separate path when there is no running process. Once systemd reports active, check the listener and then run the HTTP tests. The unit log can show activation attempts and command errors. It helps when parsing passes but a socket cannot be opened, a prior stop was incomplete, or a package override changes how the service starts. Full service restart is a different operation and can cause interruptions that a reload would avoid.

Lab one: prove the selected site and its four responses

Prerequisites are the assigned AL2023 practice host, access to its shell, the approved package and configuration from the previous sections, and the four public release files. This first check runs on that machine. For the example, curl connects to its local IPv4 loopback interface, using the shop hostname in the request. Use this form after confirming that the service listens on loopback or on the relevant wildcard address. --noproxy '*' prevents a workstation or server proxy setting from intercepting the diagnostic request.

(
set -eu
name=mauli-orders.example.test
out=$(mktemp -d "${TMPDIR:-/tmp}/mauli-order-check.XXXXXX")
trap 'rm -f -- "$out/home" "$out/css" "$out/rates" "$out/missing"; rmdir -- "$out"' EXIT
request() {
  curl --noproxy '*' --resolve "$name:80:127.0.0.1" \
    --silent --show-error --max-time 5 \
    --output "$out/$2" --write-out '%{http_code} %{content_type}\n' \
    "http://$name$1"
}
request / home
request /css/style.css css
request /rates.html rates
request /retired-offer missing
grep -F 'Mauli collection notice' "$out/home"
grep -F '.collection-hours' "$out/css"
grep -F 'Mauli rates for this training release' "$out/rates"
grep -F 'Mauli page unavailable' "$out/missing"
)

Read the four response lines in order. The first and third should have status 200 and an HTML type. The second should have status 200 and a CSS type such as text/css. The fourth should have status 404 and the HTML type of the custom error page. Type parameters such as the character encoding may appear after the MIME type. If you chose your own markers in the release files, update the four grep arguments to match them. A grep failure produces a nonzero shell status. Read the four response lines as well, because the shell sample prints HTTP statuses without enforcing them. The exit trap cleans these four diagnostic response files and their temporary folder.

If your homepage marker appears with an unexpected CSS status, fetch the stylesheet path on its own and compare it to the actual HTML link. The client can get status 200 from the first URL while receiving the custom error page for a missing dependency. If the page appears unstyled, look at the browser network panel to see which URL it requested. A stylesheet request might have gone to /about/css/style.css instead of /css/style.css if the page used a relative URL. Exact URL paths and media types make the mismatch visible.

sudo tail -n 12 /var/log/nginx/mauli-orders-lab.access.log
sudo tail -n 12 /var/log/nginx/mauli-orders-lab.error.log

Compare the four URL paths and statuses with entries near the time of your request. Check the log file names against the active configuration if you see nothing. A response observed only in another site's access log is evidence to revisit the host and listener. A 404 from the intended host is useful because it confirms the request reached your site, then found no requested resource. A local connection refusal rarely produces a new access entry because the HTTP conversation never started. Logs are shared operational data, so use your own identified request lines when recording the exercise.

Decide which parts of the AWS path need an outside test

The loopback test uses the guest's local network stack to contact Nginx. A laptop outside the instance reaches a different path. An internet-facing IPv4 lab needs a valid public destination for that instance, applicable routing and network rules, and a listening socket that accepts connections on the associated private side. The instance console shows any associated public IPv4 address. The operating system typically sees the corresponding private address on the interface. The internet gateway handles the mapping for a directly reachable public endpoint, so Nginx ordinarily binds a local address or a wildcard listener.

An external address lookup reports the address seen at the service you called. An instance behind an outbound gateway or proxy can get an answer that belongs to that gateway or proxy. Such an answer does not identify an address for incoming HTTP connections to the instance. Choose the approved destination from the EC2 resource details or from the assigned ingress setup. Before declaring an expected connection failure, check whether the exercise was intentionally given only private access. A private lab succeeds with a suitable private client or loopback evidence without acquiring an unnecessary public endpoint.

If the trainer approved a direct IPv4 check, use a client on the allowed network and set LAB_IP to the approved address shown in the exercise record. Example names ending in .test still need the per-command override. A real DNS name takes a separate step: confirm its DNS answer and repeat a normal request without the temporary override. Test that later only if the request is meant to use ordinary public resolution. Both requests should produce the expected site marker through their intended paths.

LAB_IP='REPLACE_WITH_APPROVED_INSTANCE_PUBLIC_IPV4'
curl --noproxy '*' --resolve "mauli-orders.example.test:80:$LAB_IP" \
  --silent --show-error --max-time 5 --include \
  http://mauli-orders.example.test/rates.html

HTTP is readable in transit and this lab serves only synthetic public pages. Use the site's approved HTTPS endpoint for a real customer release. If the remote request times out after the local check succeeds, inspect the destination and supported path first. A direct public address test involves the instance's network interface, the subnet route toward the internet gateway, inbound security group rules, any network ACL and the guest's configured firewall. A later lesson covers TLS and browser redirects. Verify the exact scheme, request URL and response before changing any rule.

For IPv4, an inbound security group rule can be scoped to the required HTTP port and approved source network. An SSH rule is a separate decision because it allows administration rather than site reading. Rule overlap matters: permitting an IP in one rule does not limit another rule that already permits a broader source. Read the attached security groups before changing anything and keep existing site and access rules under their owner's control. If the lab supplies a bounded rule, record that exact rule and restore it at cleanup so a test does not leave a longer-lived opening.

Lab two: test host selection without the system service

Use this alternate exercise on a machine where the nginx binary and Python 3 are already available. An installed Nginx executable from a disposable build also works. Set the optional NGINX_BIN variable to an approved absolute executable path when it is outside your shell's usual search path. The exercise starts a temporary foreground process with an independent config, PID file and logs, and a dynamically chosen unprivileged loopback port. It uses a synthetic release and never calls DNF or systemd. It demonstrates Nginx rules directly, while the first lab demonstrates the full AL2023 service procedure.

python3 - <<'PY'
from http.client import HTTPConnection
from pathlib import Path
from tempfile import TemporaryDirectory
import os
import shutil
import socket
import subprocess
import time

nginx = os.environ.get("NGINX_BIN") or shutil.which("nginx")
if not nginx:
    raise SystemExit("Use an approved local nginx binary for this lab.")
host = "mauli-orders.example.test"

with TemporaryDirectory(prefix="mauli-nginx-") as area:
    base = Path(area)
    shop = base / "shop"
    default = base / "default"
    (shop / "css").mkdir(parents=True)
    default.mkdir()
    (default / "index.html").write_text("Packaged welcome marker\n")
    (shop / "index.html").write_text("Mauli collection notice\n")
    (shop / "rates.html").write_text("Mauli rates for this training release\n")
    (shop / "404.html").write_text("Mauli page unavailable\n")
    (shop / "css/style.css").write_text(".collection-hours { color: navy; }\n")
    with socket.socket() as probe:
        probe.bind(("127.0.0.1", 0))
        port = probe.getsockname()[1]

    conf = base / "nginx.conf"
    conf.write_text(f"""
    pid "{base / 'nginx.pid'}";
    error_log "{base / 'error.log'}";
    events {{ worker_connections 16; }}
    http {{
        client_body_temp_path "{base / 'client_body'}";
        proxy_temp_path "{base / 'proxy'}";
        fastcgi_temp_path "{base / 'fastcgi'}";
        uwsgi_temp_path "{base / 'uwsgi'}";
        scgi_temp_path "{base / 'scgi'}";
        access_log "{base / 'access.log'}";
        types {{ text/html html; text/css css; }}
        server {{
            listen 127.0.0.1:{port} default_server;
            server_name _;
            root "{default}";
            index index.html;
        }}
        server {{
            listen 127.0.0.1:{port};
            server_name {host};
            root "{shop}";
            index index.html;
            location / {{ try_files $uri $uri/ =404; }}
            error_page 404 /404.html;
            location = /404.html {{ internal; }}
            access_log "{base / 'orders.access.log'}";
        }}
    }}
    """)

    args = [nginx, "-e", "stderr", "-p", str(base) + "/", "-c", str(conf)]
    subprocess.run([*args, "-t"], check=True)
    worker = subprocess.Popen([*args, "-g", "daemon off;"])
    try:
        for attempt in range(60):
            if worker.poll() is not None:
                raise RuntimeError("Temporary nginx did not start.")
            with socket.socket() as conn:
                if conn.connect_ex(("127.0.0.1", port)) == 0:
                    break
            time.sleep(0.05)
        else:
            raise RuntimeError("Temporary listener did not become ready.")

        def check(name, path, status, kind, marker):
            req = HTTPConnection("127.0.0.1", port, timeout=3)
            try:
                req.request("GET", path, headers={"Host": name})
                resp = req.getresponse()
                payload = resp.read().decode()
                assert resp.status == status, (path, resp.status)
                assert resp.getheader("Content-Type").startswith(kind), path
                assert marker in payload, (name, path)
                print(f"{resp.status} {name} {path}")
            finally:
                req.close()

        check("default.example.test", "/", 200, "text/html", "Packaged welcome")
        check(host, "/", 200, "text/html", "Mauli collection notice")
        check(host, "/rates.html", 200, "text/html", "Mauli rates")
        check(host, "/css/style.css", 200, "text/css", ".collection-hours")
        check(host, "/retired-offer", 404, "text/html", "Mauli page unavailable")
        orders = (base / "orders.access.log").read_text()
        assert "GET /retired-offer HTTP/1.1" in orders
    finally:
        worker.terminate()
        try:
            worker.wait(timeout=5)
        except subprocess.TimeoutExpired:
            worker.kill()
            worker.wait()
PY

Read the first two output lines together. They should each show 200 for the path /, yet each asserted a different body. The remaining lines validate rates, CSS and the custom 404 for the assigned host. The script constructs the correct Host header explicitly because it connects directly to a local socket using Python's HTTP client. This is the same selection decision exercised by the curl command in the machine lab. The log assertion reads only the practice log, and process termination runs even if an assertion fails. Python removes the independently created scratch directory at the end.

If the configuration test fails, first confirm the executable is a normal Nginx build with the HTTP modules this small sample uses. An error referring to an unknown directive or module can describe a different build configuration. If a process cannot bind the chosen port, the gap between selecting and opening the port may have allowed another process to take it. Run the exercise again to select a different local port. Preserve the failed diagnostic output when available. There is no reason to stop a system Nginx instance, open an inbound rule, or install anything into its system paths to repair this local test.

Choose the next check from the observed symptom

Where to look when the AL2023 setup gives an unexpected result
EvidenceNext comparisonInterpretation
DNF reports no available packageCompare the guest version and enabled repositories with the assigned image.A package-selection issue precedes website configuration.
Parsing passes but the service fails to startRead the unit journal and check who owns port 80.The active socket or running service environment may differ from the syntax test.
Expected name gives a welcome pageCompare the URL's host with server_name and look for the new block in nginx -T.The default site may be responding successfully.
/rates.html works; a nested page loses stylingRead the link path and the requested stylesheet response type.The browser may be resolving a relative link below a different parent URL.
Custom message arrives with an unexpected statusInspect the error_page directive and exact requested path.A fallback status override can hide the missing resource.
Local hostname test passes; direct remote request times outConfirm public destination, client access, routing and the actual listener.The remote request may never reach the web server.

Choose a small follow-up check that can separate two plausible causes. An access log entry for the missing offer shows the request did arrive and gives a status. A privileged file listing only verifies what the administrator can read. If the stylesheet and host are correct, examine the exact path and file modes before touching routing. When the local and outside tests disagree, compare both URLs and request headers before assuming a difference in network security. For example, dropping the host override during the outside test can legitimately select the welcome page even with every network rule working.

An apparent configuration failure can be a reader's cached response. Use a new curl process with the precise host and expected path to verify what Nginx returns now. Browser developer tools can trace its own request, including redirects and cached assets, so you can distinguish its view from the origin response. Save the release marker and status together for any discrepancy report. The person diagnosing it should be able to ask for the same path, send the same host information, and compare the resulting status and body independently.

Trace a correct file served by the wrong instance

Imagine a student has two identically named training notices because the trainer restored yesterday's instance from an image. Both run Nginx and both know the URL. On the original instance /rates.html refers to today's file, while the restored instance still serves the archived version. The hostname alone is no longer enough to tell the responses apart. Make an independent local request on the assigned instance, then make an explicitly mapped request to the intended outside address where the exercise permits it. Compare the release marker for each request and look for the outside path in the assigned site's access log.

If an ordinary browser still displays yesterday's information after the explicitly mapped request passes, read its destination and the rest of the real delivery path. Your comparison might show that a DNS answer still names the previous machine, or that a proxy has an older cached object. Ask for the same path and record any intermediate redirect before comparing bodies. A name and a deployment reference only certify the intended endpoint when verification follows the same path as the reader's request. This is also why a spare, valid machine can give a more confusing symptom than a closed port.

Hand off the lab and restore its prior state

Before publishing a later change, record the working site file, publish root and relevant checks. An administrator can make an approved private copy of the one site's configuration as a rollback reference. Keep it outside the active include glob so Nginx does not load a second copy. Write down whether the first test began with an installed package, an already-active service and an enabled boot state. When an exercise uses a pre-existing server, those prior states belong to the server owner and guide what can change at cleanup.

For the reference lab, remove only the new site file if you own it and the owner wants the original service configuration restored. Re-run nginx -t and reload the associated service only if it was kept active. When the lab started a disposable service and no other application uses it, follow the trainer's instructions to stop it. Delete the synthetic publish directory only after verifying that the active configuration has stopped referring to it. Keep the exact approved path in the exercise record to avoid deleting a parent that holds another site. If you enabled the service, restore the intended startup state separately.

On a disposable EC2 exercise, confirm the approved cleanup plan before retaining, stopping or terminating the instance. Related resources can have different lifecycles, for example a manually assigned address or a storage volume configured to persist. Use the exercise inventory to identify the resources created for this student. Check the application's shutdown separately from AWS resource cleanup, and keep the required lab evidence outside any instance that the trainer plans to remove. A shell prompt disappearing tells you only about that connection, so confirm the named instance and related resources in the appropriate AWS view.

Interview questions with worked answers

Why can two requests to the same address both return 200 and show different sites?

The address and port establish the connection. The HTTP host information helps select a particular server block. An unmatched name may select the default block. Each block can map / to its own homepage. Check the exact host and an identifiable body marker to decide which site handled the request.

How would you deploy a new site without removing the welcome site?

Inspect the effective include path, choose a unique server name and a fresh filename, prepare a separate root and add a named server block. Validate the complete configuration and reload the active approved service. Test the new name and ensure any expected default behaviour still applies. Keep the prior configuration available for comparison.

Why does a package query succeed while the website is unreachable?

The package database can show that Nginx's files are installed. The service might still be inactive, listening on another port, or unreachable through the selected network path. Check the running unit, listener, and a local request for the intended host to locate the next missing condition.

What would you record to prove a custom 404 is working?

Request a URL that does not exist beneath the intended root. Record the 404 status and the expected custom body, and match the path to an access entry for that site. The browser may render both a real 404 and a successful fallback page, so the picture alone cannot establish the response status.

Why would you avoid using an external lookup to choose the listening address?

An outside service reports the address from which the connection appears to originate. EC2 can send that traffic through NAT, an internet gateway mapping or a proxy. The inbound endpoint and the guest's local bind address may therefore differ. Identify the approved public destination from the resource and the socket from the guest separately.

Check your understanding

  1. The practice name responds through the override. A bare-address request still shows the welcome page. Which result would prove the named site works?

    Show answer

    The override request is the relevant named-site test. Verify its expected content and access log. An address-only request supplies a different host and can legitimately select the default.

  2. DNF installed the package and systemctl is-enabled nginx says disabled. Can the process still serve the lesson?

    Show answer

    Yes. An installed service can be started for the current session even if it is not enabled for boot. Check active state and the actual listener.

  3. A file was moved to mauli-orders-lab/build/index.html. The root is still mauli-orders-lab. Which mapping should you compare?

    Show answer

    For the root URL the site tries its configured index in the document root. Identify the extra build directory and decide which intended release folder should supply the document root.

  4. The custom error text looks correct, but the test reports 200 for an absent path. Did it pass?

    Show answer

    It failed the expected missing-resource behaviour. Inspect the fallback rule and any explicit status override. A normal custom error body for this fixture retains status 404.

  5. A local test passes and the outside request times out. What evidence would you inspect before changing file modes?

    Show answer

    Compare the remote target, listener and allowed network path. A successful local request shows the process could read the file for that request. File modes are unlikely to explain a failure to connect.

Practice reading deployment evidence

  1. Write a release note with the four expected response statuses and page markers. Explain which request proves CSS is really being served and which proves a missing URL returns a genuine error.

  2. For the loopback lab, switch only the requested hostname in the first homepage check to the shop name and predict which marker assertion will fail. Restore the original test after observing its result.

  3. Draw three columns for the client URL, the Nginx decision and the selected file. Fill in a row for the homepage, the stylesheet, and the missing offer. In the last row distinguish the requested resource from the body that Nginx sends.

Revision cards

DNF
The standard package manager for AL2023. A successful transaction identifies installed software, while the running state requires a separate check.
Server block
The site rule selected using the listener and request's hostname. It names the site's root and can set site-specific logs.
Document root
The published directory that anchors file lookups. The staging tree and local upload folder have different roles.
nginx -t
A configuration and file-opening check. Read warnings and verify the behaviour with a request after controlled activation.
Temporary host override
curl --resolve controls the destination for one host and port while keeping the name in the URL.
Custom 404
A useful error body sent with missing-resource status. Check the body and status together.

Official sources