Chapter 7: Static Website Hosting (3 OSes × 2 Web Servers)
7.9 Combination 4 — Ubuntu + Apache
On Ubuntu, Apache's helper commands come in handy. a2ensite selects your new definition and a2dissite removes the enabled entry for the site you name. Keep the existing default enabled for this lab. Validate and apply the configuration before checking the live response.
Ubuntu वर Apache चे helper commands कामाला येतात. a2ensite नवीन definition निवडते आणि a2dissite तुम्ही दिलेल्या site ची enabled entry काढते. या lab मध्ये default site तशीच ठेवा. Configuration तपासून apply केल्यावर response बघा.
Ubuntu पर Apache की helper commands काम आती हैं। a2ensite नई definition चुनती है और a2dissite बताए गए site की enabled entry हटाती है। इस lab में default site रहने दो। Configuration की जाँच करके apply करने के बाद response देखो।
Identify the guest and inspect the relevant package and socket. Use the expanded procedure below to add a named site to your assigned training machine.
cat /etc/os-release
apt-cache policy apache2
sudo ss -ltnp 'sport = :80'
Ravindra Bagale's Tip
Many students bring the log path from another distribution. Ubuntu’s packaged setup normally defines ${APACHE_LOG_DIR} in /etc/apache2/envvars, commonly as /var/log/apache2. Check the configured value and run apache2ctl configtest before the approved service reload.
Ravindra Bagale's Tip – मराठी
दुसऱ्या distribution चा log path वापरू नका. Ubuntu च्या packaged setup मध्ये /etc/apache2/envvars मधला ${APACHE_LOG_DIR} बघा. तो सहसा /var/log/apache2 असतो. Service reload करण्याआधी apache2ctl configtest चालवा.
Ravindra Bagale's Tip – हिंदी
दूसरे distribution का log path सीधे मत लगाओ। Ubuntu के packaged setup में /etc/apache2/envvars के अंदर ${APACHE_LOG_DIR} देखो। यह आम तौर पर /var/log/apache2 होता है। Service reload से पहले apache2ctl configtest चलाओ।
Lab
Chala, khalcha Ubuntu Apache lab kara. sudo apache2ctl -S madhe saravachya site cha hostname ani config path tapaasa. Adhipasun aslela 000-default.conf tasach theva. Assigned hostname ne request karun page madhli olakhichi line bagha.
Publish a library's public information on Ubuntu with Apache
A volunteer prepared the opening hours and membership instructions for a small library. A staff member wants a test link to review the revised instructions before letting readers use them. The volunteer has two folders of pages and one Ubuntu instance assigned to the exercise. They need to answer two particular questions. Which configuration will Apache include at its next reload, and which website does a request currently select? This lesson uses Ubuntu's Apache helper commands to make both observations explicit.
The sample website is a brochure, with an HTML homepage, an HTML membership page, a stylesheet and a custom missing-page message. The server sends those files in response to HTTP requests. A virtual host groups the decisions that identify the library and its document root. Ubuntu keeps layouts for available and enabled site files. The a2ensite command adds a selected configuration to the enabled layout, and a2dissite reverses that selection. You will inspect the changed disk state and then check the results from the running process.
Use the complete managed sequence only on an Ubuntu practice guest whose administrator authorized the Apache service and related edits. When another site already depends on the machine, leave it available and use an isolated alternative. The offline lab later in the lesson uses an existing Apache binary and its matching modules. It reproduces the critical effect of Ubuntu's enabled-site layout in a temporary tree. It sends requests on a high loopback port and leaves service startup and active configuration unchanged.
Identify the guest and check the existing listener
On the intended guest, read /etc/os-release and record the Ubuntu release printed there. Confirm any assigned EC2 instance ID and account context separately. A useful lab report identifies where each command ran, because the same directory or site name could exist on multiple machines. The first commands report existing package, service and socket state. Run these checks individually because an uninstalled package or inactive unit can legitimately return a nonzero result. If you find that the current environment is not the approved guest, stop before any privileged change.
cat /etc/os-release
id
dpkg-query -W apache2
apt-cache policy apache2
sudo ss -ltnp 'sport = :80'
systemctl is-active apache2
systemctl is-enabled apache2
The package query reports installed state. Package policy reflects which versions are known through the configured repositories and can be selected for installation. Systemd's active state can show whether a known service is running. Enablement typically describes its relationship to boot or another target. The socket check answers which program is actually waiting for TCP connections at the port. A machine with Apache installed may still have an unrelated process there. A service with boot enablement can also be stopped at this moment.
Ubuntu uses the apache2 package and service name. This differs from the httpd convention in the Amazon Linux and CentOS examples. Read the socket check before installing a package whose setup can attempt to start a service. If an existing Nginx or another Apache installation serves the address, keep its current state. An Apache exercise on a fresh, dedicated guest lets you observe the packaged defaults clearly. You can still learn the virtual host and status checks without changing a boot setting or stopping a process on a shared server.
sudo apt update
sudo apt install apache2
apache2 -v
systemctl cat apache2
sudo apache2ctl configtest
sudo apache2ctl -S
Install only after checking the assigned host. The package list refresh collects repository metadata, and the installation asks for a specific transaction. If dependency information or signatures look wrong, compare the configured sources with the trainer's approved image and record the error. The static library needs neither a PHP runtime nor a database. After the installation, compare the new unit state and listener against the initial checklist. Record the initial packaged homepage and its response status when it is part of this lab.
Read the Ubuntu Apache layout as a tree of inputs
Ubuntu conventionally uses /etc/apache2/apache2.conf as part of its main configuration, with a separate ports.conf for listening rules and folders for modules, configuration fragments and site files. The packaged main file includes enabled entries. A site definition commonly lives at sites-available/name.conf. A link at sites-enabled/name.conf makes it visible to the enabled-site include. This convention is implemented by the configuration and the Debian family helper scripts. The Apache server reads its configuration inputs, so inspect the actual file and service invocation before applying the convention to a customized machine.
ls -ld /etc/apache2/sites-available /etc/apache2/sites-enabled
ls -l /etc/apache2/sites-enabled
grep -nE 'Include|IncludeOptional' /etc/apache2/apache2.conf
grep -n 'Listen' /etc/apache2/ports.conf
a2query -s
sudo apache2ctl -S
sudo apache2ctl -M
Use the output to locate the enabled-site wildcard. A definition's .conf extension matters when the pattern selects that suffix. Make copies for review outside the enabled tree. A new backup that matches the include could be read as another vhost definition. The first named virtual host in an eligible set can also become the fallback. Ubuntu's 000-default.conf convention typically lets its packaged site sort early. Keep that link for this exercise, particularly if its appearance is your baseline evidence for an unmatched host.
The three inspection tools provide complementary facts. Files and symlinks show the candidate topology on disk. a2query -s checks package enablement state for sites. apache2ctl -S reports parsed virtual host mappings from the configuration that command read. A successful request supplies evidence from the active process. For example, a broken enabled link, unreadable config bytes or a duplicate host could make a simple enabled-state observation inadequate. Compare the enabled link, parsed name and request result before concluding that a new server rule took effect.
Ports belong to the server's listening configuration. The line <VirtualHost *:80> attaches this definition to a matching address and port group. It does not create the actual socket. The listener accepts a connection and the request hostname selects a matching virtual host in that group. That is how the packaged default and the library site can share port 80. If you ask only for the address without the library's hostname, Apache can use the eligible default instead. Write down the host and path as part of every check.
Stage an intentional library release
Use /srv/brass-library-lab as the new document root on the assigned machine. A site can use a path beyond the packaged default when Apache's scoped authorization and the operating system allow it. Prepare index.html, membership.html, 404.html and css/library.css. Put “Brass Library reading room” on the homepage and “Library membership desk” on the second page. The error document can say “Library page has moved or is unavailable”. Use .library-hours in the style sheet and link to it at /css/library.css.
First review the staged files independently of Apache. Check the HTML text, capitalization, link paths and expected version markers. The publish folder is where the approved bytes will live. Keep the project's checklists, drafts, local editor backups and private notes elsewhere. If you received a directory from another volunteer, check it for symbolic links or files that were never intended for public reading before installing the explicit release list. The web server should be able to traverse the published path and read the approved files. The person publishing the release can retain ownership.
ROOT=/srv/brass-library-lab
ls -ld "$ROOT" "$ROOT/css"
namei -l "$ROOT/membership.html"
find "$ROOT" -type f -print | sort
Compare the root in your site block with the directory containing the real homepage. The work folder and its contents are distinct, so a recursive copy can introduce a layer such as brass-library-lab/release/index.html. If the server is pointed at the outer folder, the directory index will be looked up in the wrong place. The manifest lists every chosen location. Confirm that the Apache worker can read those files under the host rules by checking the actual HTTP responses. A privileged file read demonstrates existence for the administrator and can bypass some ordinary permission checks.
Authorization in Apache and Linux permissions are separate. The scoped Require all granted in the sample grants public HTTP access to this exercise directory when a request maps there. It does not change ownership or directory modes. On a system with active confinement, additional host policy may apply. Check the system's actual rules if the modes, path and site configuration all look correct but the server returns a denial. Change only the approved directory or specific policy after identifying the evidence.
Read where the vhost will send requests and logs
Save the following as a new candidate named brass-library-lab.conf. The test name uses a reserved suffix. Use curl's address override to send that host value through the assigned guest's loopback listener. Production DNS is a separate piece of the path. The normal Apache config file belongs outside the public directory and uses a route that reads only the scope you prepared.
<VirtualHost *:80>
ServerName brass-library.example.test
DocumentRoot "/srv/brass-library-lab"
<Directory "/srv/brass-library-lab">
Options None
AllowOverride None
AllowOverrideList None
Require all granted
DirectoryIndex disabled
DirectoryIndex index.html
</Directory>
ErrorDocument 404 /404.html
ErrorLog "${APACHE_LOG_DIR}/brass-library-lab.error.log"
CustomLog "${APACHE_LOG_DIR}/brass-library-lab.access.log" combined
</VirtualHost>
The DocumentRoot gives Apache the start of its normal URL mapping and the directory block applies to that specific filesystem location. The options allow a fixed index while leaving generated directory listings turned off. The paired override directives keep .htaccess out of this sample's policy. No rewrite module is needed for the exact HTML paths and local error document. Keep the service's existing module selection unless the class is demonstrating a feature that explicitly needs a change.
The log paths use an environment variable defined by the packaged setup. On a standard Ubuntu host inspect the relevant APACHE_LOG_DIR line in /etc/apache2/envvars. It commonly points to /var/log/apache2 but the host may supply a different value. The named access and error log files belong below that configured directory. The combined log format depends on a definition supplied by the packaging or the administrator. Check these dependencies, especially if the candidate will be tested through a custom executable outside the normal Apache wrapper.
apache2ctl is a control script that supplies the package's environment to the server. Running a bare apache2 command against the standard configuration can omit variables the unit expects. This can produce messages about variables or files even if the managed service normally works. Use the normal wrapper and inspect the actual service command when diagnosing the package. If you use a shell here document to create the candidate, quote its delimiter so your interactive shell does not expand the log variable while copying the configuration.
Install a candidate, select it, and activate the accepted configuration
Write the reviewed candidate in your workspace first. To put it into the expected Ubuntu location, use the following fresh-only helper on the assigned guest. It checks that the candidate and destination have the intended types and names. Confirm that /etc/apache2/sites-available is the correct directory on your machine. The root-owned configuration tree should be writable only by trusted administrators. Coordinate the exercise so two maintainers are not changing it at once.
(
set -eu
candidate="$PWD/brass-library-lab.conf"
target=/etc/apache2/sites-available/brass-library-lab.conf
link=/etc/apache2/sites-enabled/brass-library-lab.conf
test -f "$candidate"
test ! -L "$candidate"
sudo sh -c '
set -euC
for entry in "$2" "$3"; do
if [ -e "$entry" ] || [ -L "$entry" ]; then
printf "Already exists: %s\n" "$entry" >&2
exit 1
fi
done
umask 022
cat "$1" > "$2"
' sh "$candidate" "$target" "$link"
sudo a2ensite brass-library-lab
sudo apache2ctl configtest
sudo apache2ctl -S
)
When the command runs successfully, a2ensite selects the existing definition through the enabled-site layout. Its message may invite you to reload. Read the syntax result and vhost map before taking this step. Inspect the matching link with ls -ld and readlink. Confirm which filename supplies the library block, which host and socket the block is eligible for, and which other sites remain enabled. The helper reports a successfully handled request to enable a site that is already enabled, so pair its output with these direct checks.
If the helper or either validation fails, identify which stage completed. The available file might have been installed before the attempt to create its enabled entry. If the new link exists and parsing then fails, disable only the new library site, fix or archive its candidate, and rerun the complete configuration test. Restore a valid configuration on disk even if the running process still serves its previous sites. A later restart would otherwise exercise the invalid inputs. Keep unrelated entries and module selections intact during this recovery.
# On the approved guest, choose the action for the observed unit state.
sudo systemctl reload apache2
# If the unit is inactive instead:
sudo systemctl start apache2
systemctl is-active apache2
sudo ss -ltnp 'sport = :80'
sudo journalctl -u apache2 --no-pager -n 15
Apache's managed reload usually uses a graceful operation in the expected package setup. Check the unit file for the mechanism on this guest. The currently running server must successfully read the configuration and use it to handle new requests. A successful configuration test may still leave a startup problem such as a conflicting listener or an inability to open a log in this service context. Check the service state, listen address and request outcome together. Future boot enablement is a different step and need only change if the trainer assigned it.
Lab one. Check the library's response and the retained default
Run this after placing the marked sample release and activating the assigned site on port 80. The default comparison uses a request with the direct local address. Record its result against the pre-change observation from the same guest. The library check passes its hostname to the server through the URL while curl connects to loopback. The scope is one request at a time. No DNS, firewall or browser settings are changed by these commands.
(
set -eu
name=brass-library.example.test
body=$(mktemp "${TMPDIR:-/tmp}/brass-library.XXXXXX")
trap 'rm -f -- "$body"' EXIT
curl --noproxy '*' --silent --show-error --max-time 5 \
--output "$body" --write-out 'direct: %{http_code} %{content_type}\n' \
http://127.0.0.1/
request() {
curl --noproxy '*' --resolve "$name:80:127.0.0.1" \
--silent --show-error --max-time 5 --output "$body" \
--write-out "$1: %{http_code} %{content_type}\n" "http://$name$1"
}
request /
grep -F 'Brass Library reading room' "$body"
request /membership.html
grep -F 'Library membership desk' "$body"
request /css/library.css
grep -F '.library-hours' "$body"
request /former-membership-form
grep -F 'Library page has moved or is unavailable' "$body"
)
The library homepage and membership page should both print 200 with an HTML type. The stylesheet should print 200 with text/css. The deliberately removed form URL should print 404 and contain the expected error text. The final filename requested by the client does not become a new real membership form because the error page looks good. Read the status and body together. If one of your markers differs, update the comparison only after confirming you are checking the reviewed release. The trap removes the temporary response file.
Check logs in the directory recorded in the package environment. If it is the standard /var/log/apache2, read the files that correspond to the site's configured names. Capture the path, status and time of your own requests. If a request goes to the default, the library's per-site access log may never record it, so both the returned body and the correct log location help distinguish the response.
sudo tail -n 12 /var/log/apache2/brass-library-lab.access.log
sudo tail -n 12 /var/log/apache2/brass-library-lab.error.log
A chart with “host, request path, expected content, actual status, actual substantive line” is enough to hand the result to someone else. Notice that the stylesheet is an independent request even though it belongs visually to the homepage. A CDN or proxy added later could cache it differently. For this exercise the check talks directly to the Apache listener and shows whether the selected site can supply the specific bytes and type now.
Lab two. Observe site selection in a temporary Apache configuration
This exercise needs Python 3, an available Apache 2.4 binary and its matching modules. It was designed to work with stock dynamic modules on macOS and permits selecting an approved different binary and its module directory. Set HTTPD_BIN and HTTPD_MODULE_DIR if the automatic path selection differs on your system. On packaged Ubuntu the binary is named apache2 and the modules are usually under /usr/lib/apache2/modules. Do not run the fixture as root. It builds its own config and invokes the binary directly, so standard package environment variables and helper services are outside the exercise.
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
binary = os.environ.get("HTTPD_BIN") or shutil.which("httpd") or shutil.which("apache2")
choices = ("/usr/libexec/apache2", "/usr/lib/apache2/modules", "/usr/lib64/httpd/modules")
modules = os.environ.get("HTTPD_MODULE_DIR") or next(
(p for p in choices if Path(p, "mod_mpm_event.so").is_file()), "")
if not binary or not modules or os.getuid() == 0:
raise SystemExit("Use a matching Apache binary and module set as a regular user.")
builtin = subprocess.run([binary, "-l"], text=True, capture_output=True,
check=True).stdout
load = []
for mod in ("mpm_event", "unixd", "authz_core", "dir", "mime", "log_config"):
if f"mod_{mod}.c" in builtin:
continue
path = Path(modules) / f"mod_{mod}.so"
if not path.is_file():
raise SystemExit(f"Matching Apache module not found: {path}")
load.append(f'LoadModule {mod}_module "{path}"')
with TemporaryDirectory(prefix="brass-apache-") as location:
root = Path(location)
for item in ("sites-available", "sites-enabled", "default", "library"):
(root / item).mkdir()
(root / "default/index.html").write_text("Package default for the class\n")
(root / "library/index.html").write_text("Brass Library reading room\n")
(root / "mime.types").write_text("text/html html\n")
with socket.socket() as port_probe:
port_probe.bind(("127.0.0.1", 0))
port = port_probe.getsockname()[1]
host = "brass-library.example.test"
entries = (
("000-default", "default.example.test", "default"),
("brass-library-lab", host, "library"),
)
for label, name, content in entries:
(root / f"sites-available/{label}.conf").write_text(f"""
<VirtualHost 127.0.0.1:{port}>
ServerName {name}
DocumentRoot "{root / content}"
<Directory "{root / content}">
Options None
AllowOverride None
Require all granted
DirectoryIndex index.html
</Directory>
CustomLog "{root / (label + '.access.log')}" "%r %>s"
</VirtualHost>
""")
enabled = root / "sites-enabled"
(enabled / "000-default.conf").symlink_to("../sites-available/000-default.conf")
config = root / "httpd.conf"
config.write_text("\n".join(load) + f"""
ServerRoot "{root}"
DefaultRuntimeDir "{root}"
PidFile "{root / 'httpd.pid'}"
Listen 127.0.0.1:{port}
ServerName default.example.test
ErrorLog "{root / 'startup.log'}"
TypesConfig "{root / 'mime.types'}"
<Directory "/">
Require all denied
</Directory>
IncludeOptional "{enabled}/*.conf"
""")
args = [binary, "-f", str(config)]
def check(name, marker):
subprocess.run([*args, "-t"], check=True)
proc = subprocess.Popen([*args, "-DFOREGROUND"])
try:
for attempt in range(60):
if proc.poll() is not None:
raise RuntimeError((root / "startup.log").read_text())
try:
conn = HTTPConnection("127.0.0.1", port, timeout=2)
try:
conn.request("GET", "/", headers={"Host": name})
response = conn.getresponse()
assert response.status == 200
assert marker in response.read().decode()
print(f"{name}: {marker}")
return
finally:
conn.close()
except OSError:
time.sleep(0.05)
raise RuntimeError("Isolated web service never became ready.")
finally:
proc.terminate()
try:
proc.wait(timeout=6)
except subprocess.TimeoutExpired:
proc.kill()
proc.wait()
check(host, "Package default for the class")
site = enabled / "brass-library-lab.conf"
site.symlink_to("../sites-available/brass-library-lab.conf")
check(host, "Brass Library reading room")
check("unmatched.example.test", "Package default for the class")
assert "GET / HTTP/1.1 200" in (root / "brass-library-lab.access.log").read_text()
site.unlink()
assert (root / "sites-available/brass-library-lab.conf").is_file()
check(host, "Package default for the class")
PY
Each step starts a private Apache process, obtains a case-specific response and terminates it, so it definitely reads the simulated enabled set at that step. At first the library definition is available and the requested library name receives the packaged-style fallback. With the new link included, the same name reaches the library document root and the unrelated name still gets the fallback. Unlinking only the library brings back the first behaviour when the next process starts. This models the selection achieved through Ubuntu's helper scripts, while the managed lab uses the scripts themselves and checks an actual reload.
If a module cannot load, pair the binary with modules from its package or approved build. The lab needs the modules named in its configuration and does not assume every custom build supports them. If the loopback port is claimed in the short interval between discovery and start, choose a fresh run. Inspect the error output and leave unrelated services alone. Python disposes of the temporary tree after the process exits, including both public folders and the demonstration logs.
Work through the result of four client choices
The request chooses an address and a port before Apache can see an HTTP hostname. Imagine the college uses two different training machines. Both contain a vhost named brass-library.example.test, and one contains last week's brochure. A client with the correct hostname can still receive the older version when it connects to the other machine. In your test notes, the target address identifies which service received that connection, while the host value selects the site name within that service. The document marker links the response to the expected release.
| Request | Path of decisions | Expected evidence |
|---|---|---|
| Direct IPv4 address on port 80 | A listening Apache socket can use its eligible default for an unmatched host value. | The same default marker recorded before adding the library. |
| Library hostname mapped to loopback on port 80 | The connection reaches the same app, and its hostname can select the library vhost. | A home page with the library marker and an entry in its paired log. |
| Library hostname mapped to a port without a listener | The client cannot establish the expected HTTP connection. | A connection error, with no request line to interpret in the library's access log. |
| Library name at the right listener with the former form URL | The name selects the vhost, but the requested path has no public file. | The custom body with status 404. |
On a shared service, fallback selection also depends on which groups are eligible. Apache can select a more specific address group before considering a wildcard group for the same port. For example, if a separate test block is configured only for 127.0.0.1:80, a loopback request can behave differently from a wildcard listener test at an instance address. Inspect the grouping shown by apache2ctl -S. Keep this training vhost in the expected port 80 wildcard group and test the actual approved destination if the class uses a different binding scheme.
Choose a test that follows the decision under investigation. A port check can show that the program listens, but it cannot tell whether a client named the library. A vhost map can show a correct configuration on disk, but it cannot verify the running process adopted it. The access log can show a request path, but the acceptance report should also read the content marker. These observations form a trace from machine and selected site to a specific immutable result from the client's perspective.
Decide which Apache modules this site depends on
An Apache module is a set of server features that can supply directives and process requests. The distributed base service assembles an installed module list through configuration. Ubuntu has module definitions and module enablement helpers, as well as site definitions and site helpers. Their names reflect different units of change. Enabling a site selects its vhost file. Enabling a module can add capabilities for multiple sites. Read the specific directive and its source before changing the global module list.
The brochure's directory index uses the normal directory module. The CSS content type is normally determined by MIME configuration. The public directory grant uses Apache's authorization support. There is no rule in the sample that needs URL rewriting. The ErrorDocument directive uses a local path when the response would be a 404, and its status and body can be examined directly. If the packaged server does not recognize a directive, check the effective module list with apache2ctl -M and the feature's reference. A message such as “Invalid command” can identify a missing module or a spelling error and needs evidence to separate them.
A learner might bring an old copy of another server's site that uses a per-directory rewrite file. The file is a policy decision, not part of the HTML. If the library wants to preserve an old URL, ask for the exact mapping and validate it as a documented change to this vhost. You can still serve the prepared pages directly while you review that requirement. Shared package settings should not change merely because a copied recipe recommended a module that the current sample never uses. A beginner can explain every activated feature in terms of an observed response.
Investigate a missing log before changing the server
Imagine apache2ctl configtest reports that Apache cannot access a directory for the new error log. The candidate may point to a path carried over from an Amazon Linux lesson. The standard Ubuntu root for Apache log files often differs from that path. Read the configured environment and the actual ErrorLog directive. A customization can move the log directory, so a package default is a clue and not a guarantee. Ask which account or service setup creates and owns the approved log directory.
grep -n 'APACHE_LOG_DIR' /etc/apache2/envvars
systemctl cat apache2
sudo apache2ctl configtest
sudo journalctl -u apache2 --no-pager -n 20
If the issue is an undefined variable, check how Apache was invoked. The normal Ubuntu wrapper uses the packaged environment, while a directly executed binary may not. If the variable is valid and the selected path is absent, fix the site file within the scope of the approved default or have the service owner create the intended log location. Do not make logs globally writable to make an error disappear. The path contains records about visits and needs appropriate access and retention. A local training copy of the directory can have different attributes from the running service's designated location.
Once requests succeed, take one intentional missing form request as an example. The combined access format can show the original path and final 404 result, subject to how the combined alias is defined on the host. The body is the library's custom HTML. The first record addresses what the reader asked for, while the second demonstrates the user's error experience. Log information alone cannot prove the custom text was served, and a screenshot of the custom text alone cannot prove the status or intended virtual host.
Check which links belong to the public site
A reader opening /membership.html may click a stylesheet link that starts with /css/. A leading slash makes the URL begin at the same host's web root. An ordinary relative link starts from the current URL's directory. When the library later moves a page to /readers/membership.html, the relative link may cause the browser to ask for /readers/css/library.css. Directly opening the homepage can miss this. Compare the browser's actual URL for the asset with the site manifest and test the asset itself through the intended listener.
A custom error document can encounter the same problem. It can be served internally for a missing nested path, while the browser still displays the original missing URL. Therefore a stylesheet reference based on that URL's apparent directory may select a new missing asset. The example uses a root-relative path for the public site's stylesheet. When an approved real deployment serves the brochure under a prefix rather than the entire host root, relative and root-based links need an explicit test under that prefix to appear correctly. Both cases depend on the URL the client sees.
Check content type as well as a successful HTTP exchange. The browser expects CSS for the stylesheet request. A generic fallback can return an HTML body with status 200 at that path, which is a failed asset release. A targeted curl request followed by inspection of the file marker gives clearer results than browsing the requested HTML alone. Read the Apache site log at the relevant time to distinguish an old copy of the file from a more general route error.
Read startup errors and HTTP errors separately
| Observed event | Evidence to collect next | Reason |
|---|---|---|
a2ensite reports the site does not exist | List the exact name in the available directory and verify the config root. | The helper needs the saved candidate as its input. |
| The enabled link exists but parsing fails | Open the reported filename and line, and check its target and loaded modules. | Disk selection can make an invalid candidate part of the full configuration. |
| Syntax passes and the service still fails to start | Check the listening socket and service journal. | Another program could own the port, or runtime conditions could prevent activation. |
| Browser displays a different successful homepage | Check destination, host, parsed vhost map, log and expected content marker. | An unmatched request can go to the retained default. |
| Specific public file returns 403 | Check the exact URI, directory access rule, worker access and guest security policy. | The request reached Apache but was denied in its selected context. |
| Connection refused or timed out | Compare local listen addresses, the assigned EC2 endpoint, route and permitted network controls. | Apache might never receive an HTTP request. |
If the connection comes from an approved client elsewhere, the private or external network path adds its own checks. A listening process on loopback can still be inaccessible from a private subnet or a workstation. EC2 security groups and host firewall settings act before the server's directory rules. Inspect the approved address, routing and permitted client first. A new inbound rule cannot resolve an invalid filesystem path for a request that already landed in the library's access log. A directory rule cannot start an inactive listener.
Ubuntu's guest may have a locally managed firewall and security policy. Read the configured state through the relevant administrative interface rather than guessing which controls are active. A 403 from the correct Apache vhost calls for an application and file-access check, so obtain the scope and exact denial before changing anything. An external check can also select a real DNS answer or scheme that differs from your local probe. The reserved lesson name requires explicit local or test address mapping. For a real launch, validate the intended ordinary DNS and HTTPS route separately.
Compare a proposed membership change with the current release
The librarian sees an old membership form link on the public page while a reviewer's local folder has the updated link. Compare the exact file served by Apache with the intended approved file, using the response marker to locate the release. The editor's current working directory gives you context about which draft they saved. The site map and the configured DocumentRoot establish where the active request looked for its homepage. A release review is complete only when those observations connect the reviewed bytes to the request from the right host.
Write the expected mapping first, for example “the approved membership instructions live at /membership.html in the current library release.” If the previous URL should point to the new one, treat it as separate routing work and document the intended redirect status and target. If it should disappear, test its 404 against the same host. These are different requirements even if they use the same styled error or information page. The configuration tests answer which files Apache can parse, while the acceptance requests establish how the public URLs behave.
Collect the inspection results around the precise moment of the change. For an update that adds only a static file within the current document root, the package's enabled-site list can stay exactly as before. For a change that points the site at a different root, the same link name can still select updated configuration. Someone reading only the filenames would miss this distinction. Record the active root and one identifying phrase or file digest for the approved candidate. These details make a rollback test reproduce the right release even if the rendered pages look almost identical.
Repeat the check after a controlled activation
For the acceptance handoff, use the same curl command before and after the planned reload. Keep its host, port and requested path constant. If the earlier body belongs to the default and the later body names the library, you have isolated the effect of the configuration activation. If the response text changes while both requests use the library's own log, you may instead be seeing two versions of the selected release. Note that distinction in the record.
Disable the library site and verify the fallback survives
Keep the record of what you added. On the assigned Ubuntu machine, sudo a2dissite brass-library-lab removes the enabled entry for this one site. Then run sudo apache2ctl configtest and sudo apache2ctl -S. The library should be absent from the selected vhost set and 000-default.conf should remain when it was present at the start. Apply the valid configuration with the approved reload if Apache is running. Confirm the result with the same request and record the fallback that now answers, if that is the expected behaviour.
Retain the disconnected candidate until proving cleanup. With the definition still present, the owner can select it again using the helper and the same tested activation process. Archive any approved prior version outside included directories. If you must delete the synthetic website after the exercise, wait until no active or saved exercise site needed by another reviewer points at it. The course sample path is independent of other sites and the common default directory. Confirm you are removing only the files created for the exercise.
Restore the approved package and boot-state plan rather than assuming the service should be enabled or disabled. If the class was assigned temporary AWS access rules, remove only those rules as part of the recorded cleanup. A separately allocated address or retained storage volume may have its own handoff. Use the inventory provided by the trainer. For the offline fixture the runner already stops its Apache child processes and cleans the temporary tree; it never changes service startup flags.
Interview questions with explained answers
How do you distinguish an available Apache site file from a running site?
The file is a candidate. Ubuntu can select it via an enabled link, and Apache parses selected files when validating its configuration. The service must adopt those rules for a request to reach the site. Check the included name, parsed mapping and HTTP result separately.
Why keep 000-default enabled during this lab?
Apache can host both definitions on the same port and select the library by hostname. The existing fallback can continue serving unmatched requests. Keeping it exposes how host selection works and avoids changing a separate site.
What does APACHE_LOG_DIR provide?
It gives a value for the site log path under the packaged Apache environment. On standard Ubuntu it generally refers to the Apache log directory. Inspect the actual configured value and use the package wrapper for a matching diagnostic context.
When is an Apache rewrite module needed here?
The lab uses direct static paths, a configured directory index and a local error path, so those requests require no rewrite rule. If a later requirement introduces rewrite directives, justify the exact feature and evaluate the effect of enabling a module for the service.
Which evidence would you use to diagnose a default homepage at the right IP?
Confirm the requested hostname, listener and virtual host mapping. Look at which site log received that request and which body marker came back. A successful default response can coexist with a working named site.
Check your understanding
The definition exists under sites-available but the vhost map omits it. What should you inspect first?
Show answer
Inspect the active include and enabled site link. The Apache include must reach the definition. Select the candidate with the approved helper and verify the resulting parsed map.
a2ensitesucceeds, but Apache has not reloaded. Which result do you need?Show answer
Verify the disk configuration, apply it through the assigned service and request the named site. A successful helper action does not directly change the running process.
The named library returns 200. The bare loopback address still gives the welcome page. Is that allowed?
Show answer
Yes. The hostname can select the library while a different host value goes to the default. Check the intended body for each request.
Where would you check if configuration parsing complains about an undefined log variable?
Show answer
Check the packaged environment file and the invocation. The systemd unit or Apache wrapper can supply an environment the bare binary did not receive.
How can a readable custom error message still fail the lab?
Show answer
The exercise also requires 404 for the missing URL. If the request redirected to a successful fallback or uses the wrong virtual host, the visual text alone is not sufficient.
Practice the Ubuntu Apache workflow
Sketch the path from
apache2.confthrough the enabled include and the library link to the definition. Label the step at which a new request begins using it.In the isolated exercise rename the library link to a name ending in
.savedbefore one controlled start. Predict which response appears under the same include pattern, then restore the fixture.Prepare a one-page change record for a preview reviewer. Include the exact candidate, enabled entry, listener, host, post-change acceptance paths and the site removed during the simulated rollback.
Revision cards
apache2- Ubuntu's Apache package and service name. Check the operating system before borrowing administration commands.
a2ensite- Select a saved definition for the enabled-site set. Follow with syntax and mapping checks before activation.
a2dissite- Remove a named site's enabled entry and retain its available definition for approved reuse.
apache2ctl -S- Inspect parsed virtual host names, address groups, defaults and source files.
- Packaged environment
- Settings used to start and test the Apache instance, including local directories and run identities.
- Acceptance probe
- Send the approved hostname to the correct listener and compare the selected body, media type and status with the planned result.
Official sources
- Ubuntu Apache installation and layout
- Ubuntu package management
- Ubuntu a2ensite and a2dissite manual
- Ubuntu a2query manual
- Ubuntu Apache control wrapper
- Apache virtual host matching
- Apache listener binding
- Apache root, directory and error directives
- Apache directory index module
- Apache media type mapping
- Apache access log formats
- Apache reload and stop mechanics
- Amazon VPC security groups
- curl request and address selection options
- Reserved test names