Chapter 7: Static Website Hosting (3 OSes × 2 Web Servers)
7.8 Combination 3 — Ubuntu + Nginx
On the standard Ubuntu Nginx setup, write the new definition in sites-available and select it with a symlink in sites-enabled. Test with your assigned hostname while keeping the packaged default site in place.
Ubuntu च्या नेहमीच्या Nginx setup मध्ये नवीन site definition sites-available मध्ये लिहा. sites-enabled मध्ये तिचा symlink बनवा. Ubuntu ची default site तशीच ठेवून सरावाच्या hostname ने test करा.
Ubuntu के सामान्य Nginx setup में नई site definition sites-available में लिखो और sites-enabled में उसका symlink बनाओ। Ubuntu की default site रहने दो और अभ्यास के hostname से test करो।
Check the guest, package and listener first. Follow the expanded lab below to install Nginx on a dedicated instance and stage your named site.
cat /etc/os-release
apt-cache policy nginx
sudo ss -ltnp 'sport = :80'
Ravindra Bagale's Tip
Run ls -l /etc/nginx/sites-enabled/ and verify the link for your site. A relative target is interpreted from the link’s directory and can work when it resolves to the correct file. Seeing the welcome page for localhost can be expected. Use the intended hostname for the named site test.
Ravindra Bagale's Tip – मराठी
ls -l /etc/nginx/sites-enabled/ चालवा आणि तुमच्या site चा symlink तपासा. Relative target हा symlink असलेल्या directory पासून मोजला जातो. योग्य file पर्यंत पोहोचत असेल तर तो चालतो. Localhost वर welcome page दिसू शकतो. तुमच्या site साठी तिचा hostname वापरा.
Ravindra Bagale's Tip – हिंदी
ls -l /etc/nginx/sites-enabled/ चलाओ और अपनी site का symlink जाँचो। Relative target की गणना symlink वाली directory से होती है। सही file तक पहुँचता है तो वह काम करेगा। Localhost पर welcome page दिख सकता है। अपनी site का test उसके hostname से करो।
Lab
Chala, Ubuntu var khalcha lab kara. readlink ne saravachya site cha target paha. sudo nginx -T madhe tya site chi sampurna loaded block ani file cha path tapaasa. Reload zalyavar assigned hostname ne request karun tya page chi olakhichi line tapaasa.
Prepare and enable a bakery website on Ubuntu
A bakery plans to replace a printed weekend menu with a simple webpage. The assistant copies the page and its CSS to a training machine. A second learner writes a clean Nginx server block, then they both open the browser and still see Ubuntu's welcome page. They discover the new site file is saved correctly but has never been included in Nginx's configuration. In Ubuntu's packaged setup it is common to keep a definition in one directory and select it for use from another. This is the main distinction this combination teaches.
We will follow the same site through three practical states. The definition can be prepared in a text file, enabled in the configuration on disk, and finally loaded into the running service. Then we will make a request for the name assigned to the bakery. These steps expose the difference between a correct document, a valid configuration, and an HTTP response from the selected site. They also give us a plan for undoing the bakery changes without touching a packaged welcome site or someone else's configuration.
Use the managed procedure on a dedicated Ubuntu Server instance assigned for the lesson. Where AWS access or sudo is unavailable, run the isolated exercise below. It starts a genuine Nginx binary with a temporary directory and private local listener so you can see the same include pattern in action. In both cases use public sample files only. The sample menu is fictional and the lesson does not need real orders, names, credentials or billing details.
Identify Ubuntu and read the package transaction
Begin at the system you intend to administer. /etc/os-release should identify Ubuntu. Write down its release and instance ID if it is running in EC2. The command prompt is a poor substitute for this information because users can customize it. Entering the correct machine helps before a privileged operation and later if a test seems to show content from another instance. A desktop Ubuntu machine and a classroom Ubuntu cloud image can also have different initial packages or system services.
cat /etc/os-release
id
dpkg-query -W nginx
apt-cache policy nginx
sudo ss -ltnp 'sport = :80'
systemctl is-active nginx
dpkg-query inspects the installed package database. apt-cache policy reports the versions visible through the configured package sources and any currently selected candidate. A package can be available for installation and still be absent on the guest. If the listener check shows a different service already using the lab socket, keep its original configuration. Move to a separate assigned instance or use the loopback lab. Installing a packaged daemon can invoke service setup, depending on package scripts and the system's policy, so check that before preparing the managed route.
On the assigned disposable machine, refresh the package lists and install from the approved source. The update step retrieves package information. It does not request an upgrade of every installed package. Installation resolves the chosen package and dependencies. Read the summary before accepting any changes, especially if it proposes replacing an existing package. In a restricted classroom network the repository connection might fail before Nginx even exists. Record the repository or DNS message and ask the lab administrator which source the image expects.
sudo apt update
sudo apt install nginx
nginx -v
systemctl cat nginx
systemctl is-active nginx
systemctl is-enabled nginx
Take note of the package version, current process state and boot activation separately. Seeing a version indicates that the executable exists and can start to print its version. It does not tell you where that service listens. The unit file shows how systemd invokes the daemon. It can also show whether a customized machine passes a different configuration path. When the package starts Nginx during install, you may be able to examine the initial welcome page immediately. That view is useful evidence for the later comparison.
Read the configuration include before creating any link
In the conventional Ubuntu setup, the main Nginx configuration loads a set of enabled site files from /etc/nginx/sites-enabled/. Definitions available for use can be kept under /etc/nginx/sites-available/. A symbolic link in the enabled directory points to a definition in the available directory. The enabled path participates in an include pattern. The available path by itself is normally just where administrators keep the definition. Nginx follows the OS lookup of the link when it reads the included path.
sudo nginx -t
sudo nginx -T
ls -ld /etc/nginx/sites-available /etc/nginx/sites-enabled
ls -l /etc/nginx/sites-enabled
Look for the enabled-directory include in the full configuration around the HTTP context. Some manually installed binaries read different files or an administrator may have intentionally changed the pattern. Match the full output to the Nginx executable systemd starts. You are learning the distribution convention and how to verify it, which is more durable than relying on a directory name alone. If the include is absent, writing a link there will still leave the site unknown to the daemon.
A wildcard include can match every eligible filename in that directory. A backup named weekend-bakery.old can still become an additional configuration fragment if the active pattern matches it. Keep backups in a separate approved private location. Also avoid including the same definition via both conf.d and sites-enabled. Nginx can read settings from multiple included paths, and a duplicate server block can lead to ignored names or conflicts. The full output identifies the files actually read when the tests ran.
| Observation | Evidence source | Meaning |
|---|---|---|
| Definition is saved | A regular file in sites-available | The candidate can be reviewed and edited. |
| Definition is selected on disk | Its link and the full configuration output | The include can lead to the saved candidate. |
| New settings are active | An approved reload or initial start and a matching request | The running service handled a request according to the candidate. |
| Public name reaches the site | A permitted client with the approved normal name and destination | That delivery path reaches the site and its expected version. |
A saved definition can be excellent and still invisible to the service. A linked definition can be invalid and therefore fail the configuration test. After a clean test, the existing workers usually keep their current settings until activation. Record these observations separately whenever a learner says that a site was “enabled”. In this exercise we use “enabled on disk” for the included file and use a content marker to demonstrate which configuration is actually serving requests.
Read a small include map from the configuration dump
The packaged installation can have several paths under /etc/nginx that look equally promising. An include intended for globally available HTTP settings and another intended for site blocks can both reside under the same HTTP context. The same file duplicated in two matching paths therefore can enter the config twice, even when the copies have different filenames. Think of nginx -T output as a list of read inputs with their relevant contents. Trace one site from its included file down to the declaration of the hostname, listener and root.
Read the emitted file markers around the expected block. If you only search for root, you may find both the default directory and the bakery directory and still have no idea which site or listener uses each one. Compare the file marker and a whole block before labelling the result. A file such as weekend-bakery.deactivated may be linked or read because the wildcard matches that name too. An administrator's word for the file does not make a special case in Nginx's parser.
During review, keep two questions separate. Has the parser read one declaration for the expected site? Does the declaration connect to the right worker-readable directory? The first can be answered before activating the change. The second also needs an acceptance request for the expected host and file. For a shop's menu update, compare the homepage and a deeper menu path to reveal if the root was correct and the requested file was missing. A single snippet of diagnostics can support both checks if you include the request hostname, port and marker.
Prove where a symbolic link leads
A symbolic link is a filesystem entry that stores a path to another entry. The link's own name can be different from the target name. In this lesson the two names match to make file ownership easier to track. Create the link using the full target path on your training instance, which avoids guessing which directory the target is relative to. A relative link can work as well. It is resolved from the directory containing the link, so ../sites-available/weekend-bakery is meaningful inside sites-enabled. The same text at a different location may lead elsewhere.
link=/etc/nginx/sites-enabled/weekend-bakery
ls -ld "$link"
readlink "$link"
if test -L "$link" && test -f "$link"; then
printf '%s\n' 'The site entry is a link to a reachable regular file.'
fi
readlink shows the target text stored in the symlink. When test -L is true but the regular-file check fails, the link may have a missing target or it may resolve to a different kind of object. Inspect the target rather than adding a second copy of the definition. A file or symlink can also exist at a destination where you expected to create something new. A dangling symlink can evade a check that only asks whether the destination resolves to something. Test both existence and link state before staging a new entry.
Consider what happens when someone renames the available definition while its enabled link is still present. Existing workers may keep serving the previously loaded rules. The next configuration test can fail when Nginx tries to open the dangling path. This is a sensitive state since a later reload or restart needs the on-disk file. If the bakery has already been activated, first restore a known-good candidate or prepare an owner-approved removal. The next lesson using a different web server may automate this link workflow, but the underlying distinction is still valuable.
Prepare the document root and a unique host name
For the bakery use an approved new document root, /var/www/weekend-bakery-lab. Stage index.html, menu.html, 404.html, and css/menu.css. Add a marker “Weekend bake counter” to the homepage, “Saturday menu board” to the menu and “Bakery page unavailable” to the error document. Provide a small CSS rule using .bake-counter. These markers help a learner recognize the exact body and stylesheet even when a different vhost also returns 200. Check that the published copy actually contains the reviewed versions.
Use plain files owned by the designated publisher. Nginx workers need a permitted path and readable contents. Ubuntu's packaged configuration commonly uses the www-data account for the workers, but inspect the effective user setting and existing runtime user on the assigned system. The worker does not need to own all website files to read public assets. Giving the server account write access to the whole site would change who can modify public content and is unnecessary for this lab. Follow the release mode and directory checks in lesson 7.5.
Choose weekend-bakery.example.test as the hostname for the first test. This example is a testing name. Its use in Nginx does not register it in DNS. The packaged default site can remain enabled. Nginx chooses the intended named vhost when the request uses the bakery name and reaches the relevant listener. A raw IP or localhost request can still serve the packaged default. That response does not mean the named site is missing. Request both names on purpose to see how the same address can serve different content.
server {
listen 80;
server_name weekend-bakery.example.test;
root /var/www/weekend-bakery-lab;
index index.html;
location / {
try_files $uri $uri/ =404;
}
error_page 404 /404.html;
access_log /var/log/nginx/weekend-bakery-lab.access.log;
error_log /var/log/nginx/weekend-bakery-lab.error.log;
}
This block depends on the normal HTTP context of the enabled include. It has an IPv4 listener suited to the local test and no declaration taking over the listener's default. A more complex site might need IPv6 with its own reachable address and approved listener. The try_files rule attempts the path under the site's mapping and returns a missing-resource status when its candidates do not exist. The error_page rule supplies the local body for that status. Check the HTML and CSS responses as well as the result of a deliberately missing URL.
Keep the site change and the menu release aligned
Suppose the first menu marks all listings with the CSS class bake-counter. A student updates the public stylesheet path to /assets/bakery.css in a newer release. A second student stages that CSS change but links to the first menu's root. Depending on what's stored in the tree, the homepage might be readable and its old CSS could still look plausible. Compare the staged release manifest and the root line printed from the linked configuration. The goal is to select the expected four readable paths together, not merely one successful page.
You can keep a stable configuration path and publish a corrected asset in the existing lab root, or select a separately staged root when the lab calls for a new release. Those decisions have different activation paths. A file-only addition can be visible to the server on the next direct request depending on its caching configuration. A change to the configured root needs validation and activation. Record the branch or date marker of the published sample and the candidate definition together. The checkout in your shell may include additional unpublished work that should never be introduced by pointing the site at it.
A useful exercise is to give a reviewer the URL for the menu and its stylesheet without describing your filesystem. Ask them to report the returned public markers and media types, then compare them with your staging manifest. If their browser caches the old menu, make a fresh diagnostic request to the same endpoint. If it connects to a different host or follows a redirect, compare the resulting URL first. Changes to the default server will not correct an inconsistent release, and a root change will not fix a client that requested the wrong host.
Enable the bakery definition and review the resulting configuration
Save the site block above in a new file named weekend-bakery in your working directory. Read the final source and confirm the intended hostname and root. The next shell sample assumes the normal Ubuntu include path and a new file and link owned by this exercise. Coordinate any privileged changes with the person responsible for the approved instance. The helper creates a new definition and link and then tests the complete configuration. It refuses either existing destination. Run it without another configuration change in progress.
(
set -eu
draft="$PWD/weekend-bakery"
available=/etc/nginx/sites-available/weekend-bakery
enabled=/etc/nginx/sites-enabled/weekend-bakery
test -f "$draft"
test ! -L "$draft"
sudo sh -c '
set -euC
for dst in "$2" "$3"; do
if [ -e "$dst" ] || [ -L "$dst" ]; then
printf "Existing entry: %s\n" "$dst" >&2
exit 1
fi
done
umask 022
cat "$1" > "$2"
ln -sT -- "$2" "$3"
' sh "$draft" "$available" "$enabled"
readlink "$enabled"
sudo nginx -t
)
The noclobber setting protects an existing regular configuration file from replacement. GNU ln -sT treats the enabled path as the link name rather than as a directory to copy into. Inspect the output before continuing. If link creation fails after the available file was written, the available file may remain staged while the site is not selected; resolve that partial state deliberately. If parsing fails after the link was created, remove or repair only the newly created entry and then validate again. A currently working service may still have its previous in-memory settings, even though an invalid definition is waiting on disk.
Run sudo nginx -T again and identify the loaded bakery block and its absolute include path. Its location in the output is more precise than a successful text search for a single hostname. Look for other included blocks using the same name on the same listener and investigate any conflict warnings. When the managed instance has an active approved Nginx service, apply the tested configuration with sudo systemctl reload nginx. If the unit is inactive, use sudo systemctl start nginx after the configuration is ready. Confirm that systemd reports active and see whether ss shows the intended listener.
If the service is active already, think about which version is in memory. Editing a site file or switching its symlink changes the next configuration read. It does not alter rules that workers previously loaded just because an editor wrote the file. A reload asks Nginx to read the changed set. If applying the new settings fails, the service can continue using its current settings. That continuity is useful, but your acceptance test must still report the actual response. Once you have verified the bakery name, also verify the original known default when it forms part of your exercise.
Lab one: verify the bakery and the retained default
Run these checks inside the assigned Ubuntu guest after preparing the public files, creating the link and activating the validated service. The first request uses the address directly so you can record its default response on this instance. The requests after it map the bakery name to loopback using curl's temporary address override. Make the comparison using the same local port and your assigned host. No permanent DNS or hosts-file edit is required.
(
set -eu
site=weekend-bakery.example.test
tmp=$(mktemp "${TMPDIR:-/tmp}/bakery-body.XXXXXX")
trap 'rm -f -- "$tmp"' EXIT
probe() {
curl --noproxy '*' --resolve "$site:80:127.0.0.1" \
--silent --show-error --max-time 5 --output "$tmp" \
--write-out "$1 %{http_code} %{content_type}\n" \
"http://$site$1"
}
curl --noproxy '*' --silent --show-error --max-time 5 \
--output "$tmp" --write-out 'default %{http_code}\n' \
http://127.0.0.1/
probe /
grep -F 'Weekend bake counter' "$tmp"
probe /menu.html
grep -F 'Saturday menu board' "$tmp"
probe /css/menu.css
grep -F '.bake-counter' "$tmp"
probe /expired-menu
grep -F 'Bakery page unavailable' "$tmp"
)
For the bakery, expect three 200 responses for the homepage, menu, and CSS and a 404 for the absent menu. Both HTML pages should return HTML and the stylesheet should have a CSS media type. The response for the bare address can still be Ubuntu's packaged welcome content or another default that the trainer designated. Compare it to the initial evidence collected before your change. The command reports its status. If you need to compare its body as well, make an additional direct request and inspect the current contents of the correct site marker separately.
The CSS test is an important second signal. A valid homepage may appear visually plain if a browser resolves its stylesheet under a different path or gets an HTML error document where it expected CSS. Inspect the actual request URL and content type before moving the directory or changing permissions. When the direct curl test gets 200 with the right CSS marker but your browser view remains wrong, check the reference in the served HTML and the browser's request and cache history. A fresh browser load alone can be misleading if it still uses a different hostname.
sudo tail -n 15 /var/log/nginx/weekend-bakery-lab.access.log
sudo tail -n 10 /var/log/nginx/weekend-bakery-lab.error.log
sudo journalctl -u nginx --no-pager -n 18
Use the site logs to connect the reported statuses to the named virtual host. Which access lines prove that the released responses came from the bakery? Which line represents a deliberate missing resource? A failed host match may show up under a different server. In contrast, the systemd journal can reveal configuration or process problems while there has never been an accepted HTTP connection. Read each source for the event it is expected to record.
Lab two: observe a site appear and disappear through the include link
On a machine with Python 3 and a usable Nginx binary, run this ordinary-user exercise. If the binary is outside the shell's search path, set NGINX_BIN to its approved path. The exercise constructs private equivalents of sites-available and sites-enabled, then serves a temporary fallback before adding the bakery link. It tests on an available loopback port with both configuration and process supervision scoped to a temporary directory. This command needs no existing system service or network exposure.
python3 - <<'PY'
from http.client import HTTPConnection
from pathlib import Path
from tempfile import TemporaryDirectory
import os
import shutil
import signal
import socket
import subprocess
import time
binary = os.environ.get("NGINX_BIN") or shutil.which("nginx")
if not binary or os.getuid() == 0:
raise SystemExit("Use an approved nginx binary as a regular user.")
name = "weekend-bakery.example.test"
with TemporaryDirectory(prefix="bakery-includes-") as area:
p = Path(area)
for dirname in ("sites-available", "sites-enabled", "fallback", "bakery"):
(p / dirname).mkdir()
(p / "fallback/index.html").write_text("Original fallback\n")
(p / "bakery/index.html").write_text("Weekend bake counter\n")
with socket.socket() as address:
address.bind(("127.0.0.1", 0))
port = address.getsockname()[1]
definition = p / "sites-available/weekend-bakery"
definition.write_text(f"""
server {{
listen 127.0.0.1:{port};
server_name {name};
root "{p / 'bakery'}";
index index.html;
}}
""")
config = p / "mini.conf"
config.write_text(f"""
pid "{p / 'nginx.pid'}";
error_log "{p / 'error.log'}";
events {{ worker_connections 24; }}
http {{
client_body_temp_path "{p / 'client'}";
proxy_temp_path "{p / 'proxy'}";
fastcgi_temp_path "{p / 'fastcgi'}";
uwsgi_temp_path "{p / 'uwsgi'}";
scgi_temp_path "{p / 'scgi'}";
access_log "{p / 'access.log'}";
types {{ text/html html; }}
server {{
listen 127.0.0.1:{port} default_server;
server_name _;
root "{p / 'fallback'}";
index index.html;
}}
include "{p / 'sites-enabled'}/*";
}}
""")
args = [binary, "-e", "stderr", "-p", str(p) + "/", "-c", str(config)]
subprocess.run([*args, "-t"], check=True)
process = subprocess.Popen([*args, "-g", "daemon off;"])
def wait_for(expected, label, hostname=name):
for attempt in range(60):
if process.poll() is not None:
raise RuntimeError("Private nginx exited unexpectedly.")
conn = HTTPConnection("127.0.0.1", port, timeout=2)
try:
conn.request("GET", "/", headers={"Host": hostname})
response = conn.getresponse()
if response.status == 200 and expected in response.read().decode():
print(f"{label}: {expected}")
return
except OSError:
pass
finally:
conn.close()
time.sleep(0.05)
raise RuntimeError(f"Expected marker not returned: {expected}")
try:
wait_for("Original fallback", "available file only")
link = p / "sites-enabled/weekend-bakery"
link.symlink_to("../sites-available/missing-definition")
bad = subprocess.run([*args, "-t"], capture_output=True, text=True)
assert bad.returncode and "sites-enabled/weekend-bakery" in bad.stderr
print("broken link: configuration test rejected")
wait_for("Original fallback", "previous process still serving")
link.unlink()
link.symlink_to("../sites-available/weekend-bakery")
subprocess.run([*args, "-t"], check=True)
wait_for("Original fallback", "included on disk before reload")
process.send_signal(signal.SIGHUP)
wait_for("Weekend bake counter", "after enabling and reloading")
wait_for("Original fallback", "unmatched host", "other.example.test")
link.unlink()
assert definition.is_file()
subprocess.run([*args, "-t"], check=True)
process.send_signal(signal.SIGHUP)
wait_for("Original fallback", "after disabling and reloading")
finally:
process.terminate()
try:
process.wait(timeout=6)
except subprocess.TimeoutExpired:
process.kill()
process.wait()
PY
Follow the output in order. Initially the definition exists but the include does not select it. A deliberately dangling link causes the syntax check to fail and does not change the running process because the exercise has not asked it to reload. The next link resolves correctly, so the test passes. The response still shows the fallback before the reload. After the reload the assigned bakery name shows its own content while a different name still shows the fallback. Finally the named site is removed from the active set and the original candidate remains saved.
Everything is inside the temporary directory, which is removed after the private Nginx child has stopped. An unusual lean binary may lack some common HTTP modules whose temp path settings this sample config uses; use a build compatible with the fixture. Another process can claim the chosen loopback port after the probe releases it. If binding fails, rerun the exercise to choose a different one. The ordinary system service is outside this test. You can compare the observed include semantics with the main exercise without using them to infer any particular package or systemd state.
Identify which of the three states still needs work
Keep three observations on the same line of your change notes: the expected candidate name, the include entry that resolves to it and the actual marker returned by the intended hostname. If the first two are correct and the old response also has status 200, compare which process and listener answered. Then verify actual activation. A typo in the requested name and a missed reload can produce the same visual symptom although they call for different fixes.
| Observed result | Check the specific dependency | Expected observation |
|---|---|---|
Available definition exists but is absent from nginx -T | Check the active include path and inspect the enabled link. | The selected path resolves to the reviewed definition inside a loaded context. |
| Syntax test fails when opening the link | Compare the stored target with the files in the available directory. | The absolute or relative target sequence leads to an existing site definition. |
| Syntax passes but the named site gives fallback | Compare name, port, effective block, reload state and request logs. | The requested name is recognized by the active eligible server block. |
| Expected HTML loads but menu CSS is wrong | Fetch the exact linked path and inspect its type and marker. | The response contains CSS from the approved root. |
| Local requests pass and the permitted external client times out | Confirm the approved address, listener and network controls. | The service binds an address reachable through the intended external or private route. |
For example, a learner reports that nginx -T shows their new server_name. The test URL is still http://127.0.0.1/. First repeat the request with the bakery host before touching the default. If it still shows the old site, compare the current process with the config tested and read the journal near the reload. A build with a separate prefix could be running a different configuration. Capture the relevant process, configuration and request paths together to distinguish the possibilities.
Another learner saves the link as enabled-weekend-bakery in the wrong directory. They see a valid target when running readlink, and the syntax test passes. A valid symlink only shows that the filesystem can locate the file when that path is used. The include pattern has to reach it. Verify the listed file origin in nginx -T to make the difference visible. Moving or adding arbitrary files to system directories would give you more input to diagnose. Place only the planned link at the confirmed path.
Compare the loopback check with the approved remote path
The loopback exercise proves the server understands a local request for the name and path. It does not traverse the actual route from a learner's laptop. If the assigned instance is private, use a permitted private client or the trainer's designated access path. An internet-facing exercise needs an approved public destination and the appropriate AWS routing and controls. Identify the actual destination from the assigned resource record. A service answering you on 127.0.0.1 is not evidence that any public address exists.
On Ubuntu an administrator can inspect whether UFW, the Uncomplicated Firewall interface, is available and active. If the trainer assigned a guest firewall, sudo ufw status verbose is an inspection command. Security groups filter at another layer of the cloud path. A rule in one layer does not create a listener and does not authorize the same path through the other layer. Use your exercise's bounded HTTP rule and keep administration paths controlled by the owner. The public sample does not warrant disabling a host firewall or opening administrative ports widely.
Write down the precise listener value you verified. An Nginx server that listens on IPv4 port 80 does not establish an IPv6 path or a port 443 HTTPS path. A browser may have chosen a DNS IPv6 answer, attempted HTTPS, or automatically followed a redirect. In that case compare its actual destination, scheme and host with the local probe. You can repeat a specific approved external IPv4 HTTP request with a one-command address override, or request the assigned real DNS name to exercise its actual records. They answer different questions about the delivery path.
Policy controls can also affect the filesystem reading path after a request reaches Nginx. Ubuntu supports AppArmor. Its configured profiles depend on the image and package setup, so investigate using the host's own evidence if ordinary file permissions look correct but a request is denied. A named-site access entry with a 403 points back toward how the server mapped and handled that request. A timeout with no corresponding accepted HTTP exchange calls for inspection of the preceding network path. Preserve the smallest relevant logs to discuss with the lab owner.
Compare a staging name and a production-style name on the same listener
In a larger setup the bakery might need one name to approve the Sunday draft and another for a published Saturday menu. For a classroom simulation you can give each test name a separate recorded root and marker. This differs from using two aliases for one server block. Aliases are additional names intended to go through common settings and read the same published root. Separate candidate blocks help when review and release need different content or other policies. Neither case requires changing the default just to make a named request work.
Design the tests before linking a second definition. Write down which host should show which fictional date, and keep each directory private unless its files are ready for the lab. Use a loopback request override for each host at the shared port. Test both even after only one site changes, because a duplicate name or accidentally reused root can make both respond with the same content. Test the known unmatched host separately if the packaged fallback is part of the expected behaviour. These checks explain why it is common to share one HTTP listener when names and site rules distinguish requests.
When a trainer asks students about the word “staging,” clarify which kind they mean. There is a local file tree waiting to be published, an available server definition waiting to be linked, and potentially a real preview site that clients can request. A real preview site is already active for its configured delivery path. It may need network or authentication controls appropriate to the content. The synthetic loopback fixture keeps all preview bytes local and can demonstrate the same name choice without exposing an unfinished draft to an outside reader.
Disable the exercise site while keeping its candidate
For the bakery, enabling created a regular file in one directory and a link in another. For a reversible disable, confirm that the link still resolves to the candidate you created. Remove only that enabled link after the owner approves. Keep the available file and published tree during the first verification. This lets you recover the definition if you still need it and prevents a failed reload from leaving active workers with a departed root. An approved copy of the definition belongs outside any active include directory.
After changing the link, validate the complete configuration and reload the managed service if it was active. Repeat the assigned hostname test and expect the fallback or the lab's other designated response. Use nginx -T to verify the bakery block is absent from the selected config. Then check that the original default response still appears through its test path. Removing the link by itself cannot prove which rules the running workers currently use. The separate checks after reload show the intended site state.
If reactivation is needed, restore the exact previously reviewed link to the existing candidate. Inspect the target and repeat validation, reload and the same acceptance requests. Avoid relying on a different file with the same name in an old backup because the request behaviour may vary. After the final removal, delete just the disposable site definition and public files if the exercise calls for it. Keep required logs according to the lab's retention policy and restore only the cloud or firewall exceptions created for this exercise.
A compact handoff can say that the named site moved from defined to included and then served four identifiable responses, with the packaged default still present. Add where the site ran, whether testing was loopback or through a separate permitted client, and which release marker appeared for the menu. If the machine is disposable, list any additional resources created for this run and their cleanup status. That record gives a future student enough information to reproduce the exercise without assuming that every Ubuntu instance shares the same configuration.
Write a change note someone can use during recovery
For the bakery lab, list the approved source of the definition before activation and the target printed by readlink. Add the expected hostname and the specific file marker, then collect the expected post-change status for the menu and its missing path. If a reload did not take effect, record that observation separately from the fact that a definition exists on disk. Another operator can use the note to reproduce the request and to restore the exact selection that produced the last approved menu.
Interview questions with explained answers
Why might an Ubuntu Nginx site in sites-available have no effect?
The process follows its configured includes. In the packaged arrangement the available file is a candidate, and the enabled directory is read. Make the approved link, validate that the file is included, then activate and test the running service.
Can a relative symlink work between the two directories?
Yes. Its relative path begins from the directory holding the link. In the standard layout ../sites-available/weekend-bakery can lead to the intended file from sites-enabled. Verify the target text and that the result exists.
Why can the new site and the packaged default both remain enabled?
The server can select a named block for a matching host at its listener. Other host values can select the default. Test the named bakery route directly and compare an intentional unmatched request to verify both.
What is different about the syntax test and a service reload?
The syntax test examines the configuration that would be loaded. A reload asks the existing daemon to adopt it when possible. A correct HTTP response after a controlled reload gives evidence from the process actually handling the request.
Should the website files all be owned by www-data?
The workers need to traverse the approved directories and read public files under host policy. The publishing identity can own them. Giving the worker account write ownership unnecessarily changes who can alter published material.
Check your understanding
A bakery file exists in sites-available, but no enabled entry leads to it. Which state has it reached?
Show answer
It is saved as an available definition. Confirm the active include convention and add only the approved link to select it on disk.
The site link exists, but
readlinkshows a target that was renamed. What should you test next?Show answer
Check whether the stored target resolves from the link's directory. Restore the intended target or repair the link before any reload. Verify the full config afterward.
The package welcome page responds to a direct localhost check after the bakery deploy. Does that show the bakery failed?
Show answer
The request can select the default. Request the exact bakery hostname at the approved listener and check for the bakery's marker and its site log.
Why can a backup called
weekend-bakery.oldcause trouble in the enabled directory?Show answer
The wildcard include can load that file too. Keep backups outside the active include tree and check the rules read by Nginx next time you validate.
When does a removed link stop affecting a running site?
Show answer
After the service adopts a configuration that omits it. Validate on disk, reload appropriately and check both the named request and the continuing default path.
Practice the enablement handoff
Draw the path from the main configuration to the enabled link to the available file, and label where Nginx's include evaluates it.
Compare the two fixture requests that return “Original fallback” before and after linking. Explain which file is now included and why the response did not change yet.
Prepare a short rollback checklist for this specific site. Include the exact item you would remove, the validation command and one request that proves the unrelated default still behaves as expected.
Revision cards
apt update- Refresh the Ubuntu package lists. Installing the chosen package is a separate operation.
- Available definition
- A saved site file that administrators can review without making it part of the running server.
- Enabled entry
- A path selected for configuration reading. In the standard layout it can be a symbolic link to the available definition.
- Relative symlink
- A target path evaluated from the directory holding the symlink. Use that starting location to explain a broken path.
- Default block
- The fallback server for eligible connections whose requested hostname does not match another site.
- Graceful configuration change
- Verify the complete disk configuration, apply it through the approved service action and test a meaningful new response.
Official sources
- Ubuntu Server Nginx installation
- Ubuntu Server Nginx site configuration
- Ubuntu package management
- Ubuntu guest firewall
- Ubuntu AppArmor
- Nginx configuration includes
- Nginx host selection
- Nginx HTTP mapping and error handling
- Nginx command options
- Nginx running configuration control
- GNU link creation and destination options
- Linux symbolic link semantics
- VPC security groups
- curl temporary address selection
- Reserved example and test names