Chapter 7: Static Website Hosting (3 OSes × 2 Web Servers)
7.7 Combination 2 — Amazon Linux 2023 + Apache
Now the same kind of site on Apache. Check which process already owns port 80. Use a fresh assigned instance for the Apache service or take the isolated loopback exercise if another service uses that port.
आता तशीच साइट Apache वर. आधी port 80 कोण वापरतो ते तपासा. Apache service साठी सरावाचा स्वतंत्र instance वापरा. दुसरी service त्या port वर असेल तर खाली दिलेला वेगळा loopback lab करा.
अब वैसी ही साइट Apache पर। पहले जाँचो कि port 80 किसके पास है। Apache service के लिए अभ्यास का अलग instance इस्तेमाल करो। उस port पर दूसरी service चल रही हो तो नीचे दिया हुआ अलग loopback lab करो।
Start with the guest identity, port owner and Apache package details. The expanded procedure below shows the scoped site configuration and HTTP checks.
cat /etc/os-release
sudo ss -ltnp 'sport = :80'
sudo dnf info httpd
How Apache picks the site
With name-based virtual hosts, the first <VirtualHost *:80> loaded is used for any request whose Host does not match another vhost. Since ours is the only vhost, it answers requests to the public IP too. Add ServerAlias www.example.com when you have a domain.
Ravindra Bagale's Tip
Many students copy AllowOverride All and Options -Indexes without understanding them. -Indexes removes generated directory listings. A known readable file can still be fetched by its URL. Use the administrator-managed directory settings below for this static site, with overrides disabled for its root.
Ravindra Bagale's Tip – मराठी
खूप students AllowOverride All आणि Options -Indexes चा अर्थ न समजता copy करतात. -Indexes मुळे server folder ची list बनवत नाही. वाचता येणाऱ्या file चा URL माहीत असेल तर ती उघडता येऊ शकते. या static site साठी खाली दिलेले directory rules वापरा आणि त्या root साठी overrides बंद ठेवा.
Ravindra Bagale's Tip – हिंदी
बहुत students AllowOverride All और Options -Indexes का मतलब समझे बिना copy करते हैं। -Indexes से server फ़ोल्डर की सूची नहीं बनाता। जिस फ़ाइल को पढ़ने की अनुमति है, उसका URL पता हो तो उसे खोला जा सकता है। इस static site के लिए नीचे दिए directory rules लगाओ और उस root के overrides बंद रखो।
Lab
Chala, khalcha lab kara. Saravachya site cha hostname vaprun homepage tapasa. Mag index naslela samples/ folder ani tyachmadhli handout.txt file vegveglya request ne tapasa. Folder la 403 ani file la 200 milato ka te paha.
Serve a public association notice with Apache on AL2023
A small housing association wants to put its meeting schedule and office hours on an EC2 practice instance. The secretary has a homepage, a printable schedule, and a stylesheet. At a rehearsal, the secretary opens an old link to a folder that holds next month's draft and sees a generated list of names. The public link was supposed to lead to a prepared page. An Apache site needs to serve intentional files and decide what to do when a request reaches a directory without a homepage. That decision is as much a part of the website as choosing where the HTML lives.
This lesson connects three kinds of Apache settings to behaviours you can verify. The listener receives the connection, a named virtual host selects the public site, and a directory policy determines how files may be used below its document root. A virtual host is a group of settings for one website served by the same Apache installation. In the exercise the website is a set of public sample files. The server reads those files for an HTTP response and applies a consistent rule for missing resources and directory requests.
Use a fresh Amazon Linux 2023 instance assigned to you for server changes. Keep a separate local fixture when you share a machine or when another service already owns the lesson listener. The fixture later in this page exercises real Apache directory and virtual host rules using a private configuration and a high loopback port. It needs no AWS networking, administrator access, or permission to stop any existing service.
Separate the Apache exercise from an Nginx service already in use
Both Apache and Nginx can listen on TCP port 80. If one process owns a listening address and port, a second ordinary service may fail to bind the same socket. Port 80 is only part of the socket description. A process listening on all IPv4 addresses normally claims that port more broadly than one bound to a specific IPv4 address. IPv6 can introduce another listener and implementation details. Read the actual listening sockets and Apache's configured Listen directives before deciding what can start.
cat /etc/os-release
hostname
sudo ss -ltnp 'sport = :80'
rpm -q httpd nginx
systemctl is-active httpd
systemctl is-active nginx
In the guest you should see Amazon Linux and version 2023 in the operating system file. The hostname helps confirm you are in the expected shell, and the EC2 instance record is a more durable identifier for your notes. The filtered list from ss shows local TCP listeners at the port and, when allowed, their processes. A masked or missing unit can give a non-successful systemctl status. These are discovery commands you can run individually. On a fresh practice machine the absence of both packages may be a valid result.
If the output names Nginx, find out which work it serves. Stopping it would take down all sites on that process, and disabling it changes future startup. A private Apache process on a high local port can demonstrate the lesson without either change. If the task requires an actual AL2023 managed service on port 80, use an assigned unused host. A separate machine also gives a clean comparison of package defaults, logs and service names without forcing any unrelated site to switch servers.
| Situation | Available path | Evidence you obtain |
|---|---|---|
| Fresh assigned AL2023 server with a free port | Install and verify the managed httpd unit. | Package, effective configuration, systemd lifecycle and HTTP evidence. |
| Another process serves port 80 | Use the high-port loopback fixture or a separate training instance. | Site rules from the fixture, or the full service path on a dedicated host. |
| No AWS access available | Run the fixture where an approved Apache binary is already installed. | Verified index, directory and custom-error behaviour with local responses. |
It is possible to build multi-tier deployments in which one web server forwards selected requests to another. That is a different exercise involving additional routing and proxy trust. Here Apache can serve the files directly. Fix an address conflict at the level of the exercise placement first. That keeps the HTTP results easy to interpret and avoids turning a directory policy lesson into a change to another service.
Find the Apache package and its effective configuration
The Amazon Linux 2023 repository supplies Apache under the package name httpd. The systemd unit is also httpd. An Ubuntu lesson uses a different package name, different service convention and a different layout. Run sudo dnf info httpd first if you want to see the configured source before approving a transaction. Install only the web server for this static site. PHP and a database are separate components needed by some applications, and this preview has neither a server-side script nor a database record to query.
sudo dnf info httpd
sudo dnf install httpd
rpm -q httpd
httpd -v
systemctl cat httpd
sudo apachectl configtest
sudo httpd -S
sudo httpd -M
Consider each result a different observation. The package system identifies installed files and version. The binary can report its compiled Apache version. The unit definition points to the service command and any applicable overrides. The configuration test verifies it can parse the loaded settings. Using httpd -S lists virtual host mappings and their file positions, and httpd -M lists loaded modules. A module is a component that supplies a group of HTTP server features. A directive can fail to parse if the modules required by the site were never loaded.
The AL2023 RPM layout normally puts main configuration under /etc/httpd. Inspect its actual includes, often a main file under conf, module snippets under conf.modules.d, and site snippets under conf.d. Check the unit's executable and arguments if it was customized. Find the main Listen setting, confirm the relevant site file pattern and examine loaded modules for directory indexes, MIME types and authorization. If you see an IncludeOptional pattern, a missing candidate can be skipped rather than causing a parser failure. The virtual host listing will show whether the candidate was read.
Record active state before changes with systemctl is-active httpd. Use systemctl is-enabled httpd to record its startup state. New installation and current process state are separate. Enable automatic startup only when that is part of the training plan. A fresh lab can finish its first HTTP exercise without changing what will happen after reboot. If a reload does not adopt the site, compare the command shown in the systemd unit with the command you used for the configuration test. Administrative substitutions can give different effective configurations.
Distinguish the service manager's file from the web server's file
A learner changes the schedule site's configuration and asks systemd to reload its manager settings. The command completes, but the old response stays in place. Systemd's unit metadata controls how to supervise the Apache process. The site's ServerName, file paths and directory rules live in Apache's own loaded configuration. The normal service reload asks the managed Apache process to adopt its updated server files. Systemd's manager reload applies systemd unit metadata changes. You can keep the packaged unit in place while building and updating the small association site.
When checking unusual behaviour, compare the unit's binary and any flags with your direct diagnostic command. Suppose the unit invokes a nondefault file via an explicit config argument. Running the system binary without that argument could inspect a different configuration. An apparently successful test would then tell you about the wrong set of vhosts. In this main exercise use the packaged service without overrides. If the lab image was customized, have its owner identify the supported command that exercises the same file and process configuration. Writing an independent fixture is precisely how we make a different configuration explicit.
The same distinction applies when editing file bytes. If the secretary changes only schedule.html within the currently selected release, the next direct request can read the newly published bytes without changing any vhost settings. The browser may still reuse previously cached content depending on response and cache state. Read the updated file and then obtain a fresh direct response. If you change DocumentRoot to select a separate release directory, that is an Apache configuration change and needs the normal configuration validation and controlled activation.
Read the virtual host map before and after adding a site
A listener is the socket at which Apache accepts connections. A Listen 80 directive in the main configuration creates the requested port binding, subject to the host's socket availability. A block such as <VirtualHost *:80> groups settings for requests received at a matching address and port. Declaring a vhost for port 8080 does not by itself make an HTTP process listen there. This distinction matters when a copied lab shows a new number inside the block but still starts with the packaged Listen of 80.
Once Apache identifies a matching address and port group, it uses the request hostname to choose among eligible virtual hosts using ServerName and any ServerAlias directives. For an unmatched name the first vhost in the relevant group can serve as the default. The main server's response before you added that group may therefore differ from the response to unmatched names afterward. A first site on a clean instance can legitimately become the default. On a shared instance preserve the existing group order and fallback behaviour through the site's approved configuration process.
For this exercise use housing-board.example.test. It is a practice label, so send a local test with curl's --resolve option. The command keeps the host value in the HTTP request and directs the connection to the guest's loopback address. A future DNS name or real deployment should be checked separately through its approved path. Changing ServerName does not create a DNS record. Configuring DNS to point to this EC2 instance does not invent the virtual host. Both decisions must describe the intended site when the learner moves beyond the isolated preview.
sudo httpd -S
sudo apachectl configtest
Save the initial result and run the same checks once your assigned site file is in the verified include location. The new hostname, its port and the source file or line should be visible. Read any duplicate or unusual mapping before starting the service. On your dedicated lab instance also observe what the old unmatched request returns. That comparison is useful training because Apache can choose a default based on grouping and file order even though you never wrote a directive named “default”.
Choose a directory policy for a deliberately public release
Make an approved public root such as /var/www/housing-board-lab and prepare these entries: index.html, schedule.html, 404.html, css/notice.css, and a temporary practice subdirectory called samples. The subdirectory should hold one harmless plain text sample and no directory index. Use the expanded copying exercise from 7.5 for the staging and permission approach, adapting the list for this example. Inspect the root and use regular files. Keep private drafts, backups, and admin notes in an entirely different directory outside the served tree.
The DocumentRoot tells Apache where to start the normal URL-to-file mapping. A matching <Directory> block applies rules to the filesystem path. Write the complete path enclosed in double quotes when configuring the site and check that this is the same path you prepared. An Apache <Location> section deals with URL space and serves different purposes. For an ordinary static-root policy, think in terms of the site's directory and real publish files rather than trying to write a separate permission rule for every visible URL.
Apache's Require all granted is an HTTP authorization rule for that public subtree. An ordinary anonymous client is allowed by that rule to request a readable document there. Operating system controls still apply. A worker cannot open a file when the guest's permissions or security policy deny it. Check every parent directory and the public file's read access, particularly if you published from a login home directory. The public HTTP rule should be tightly tied to the sample root and should leave more private configuration or staging directories outside its scope.
Options None sets no optional directory features for this exercise. It keeps generated directory indexes, CGI execution through the ExecCGI option, and symbolic-link following options out of this scoped rule. Using Options -Indexes alone is possible when you intentionally want other inherited options, because a minus form removes only that item. Our sample release uses regular files and has a clear site policy, so setting the whole options value makes it easier for a beginner to explain what happens in the new directory.
This exercise sets both AllowOverride None and AllowOverrideList None. Together they keep Apache from reading .htaccess in the configured subtree and leave its options in the administrator-managed configuration. Some shared hosting environments let publishers use selected per-directory overrides because the publishers lack access to the main configuration. That is a different division of responsibility. Our exercise controls the site's vhost and directory directly. Keeping the rules together lets the trainer review the expected index and authorization policy alongside the root.
Disabling generated listings does not make the files in a directory confidential. A reader who knows the exact URL for the sample file can still request it if that URL maps to a readable, authorized document. This is why the directory contains only synthetic public material. The lab intentionally tests both the folder request and a direct request for its file. That pair shows where directory presentation and document authorization make different decisions.
Resolve a legacy folder rule before moving the public files
Suppose the association received a copy of a previous volunteer's website. It includes a hidden .htaccess containing a rule that sends /meeting to /schedule.html. Your new release defines all policy in configuration and ignores these per-directory files. Copying the visible pages alone therefore does not preserve the old route. Ask which old URLs need to continue working. Inspect any existing approved request rules and document an intentional mapping for each maintained URL. Build those decisions into the scoped vhost rather than assuming the old rule travels with the HTML.
In the new static lab do the smaller reversible test first. Verify the actual /schedule.html file and make the homepage link point to it. Request /meeting separately and check whether its expected behaviour is 404 or a redirect approved for a maintained URL. If there is a redirect, the source response should be a new instruction from Apache and the destination should still return the expected body and type. Record both URLs. Changing many directories and redirects in one action makes it harder to tell which rule was responsible for a successful test.
Read the effective rules for the entire public tree when importing a configuration from another host. A broader configuration can define a directory rule outside your vhost or apply a more specific policy to a subdirectory. Looking only at a single directory snippet does not reveal every eventual decision. On this fresh isolated release we control the root and use synthetic files, so validating direct requests under css and samples provides practical evidence that the expected defaults still apply.
Stage and apply the association virtual host
Save this block as housing-board-lab.conf in your learner workspace. It assumes the assigned RPM configuration already listens on port 80 and includes its site snippets. Its log names are unique for the exercise, and the access log uses the packaged combined format alias. Verify that this alias is defined in the approved configuration before using it. The path to the error document begins with a slash so Apache uses a local URL path for that body. A full external error URL would lead to a redirect and change what the client sees.
<VirtualHost *:80>
ServerName housing-board.example.test
DocumentRoot "/var/www/housing-board-lab"
<Directory "/var/www/housing-board-lab">
Options None
AllowOverride None
AllowOverrideList None
Require all granted
DirectoryIndex disabled
DirectoryIndex index.html
</Directory>
ErrorDocument 404 /404.html
ErrorLog "/var/log/httpd/housing-board-lab.error.log"
CustomLog "/var/log/httpd/housing-board-lab.access.log" combined
</VirtualHost>
The two index directives reset the index list and then add index.html. This makes the trained URL behaviour independent of any different entries inherited from elsewhere. The module interprets a directory request such as / and can then serve the public index file. If you request /samples/, the same index filename is looked up within samples. When no index exists and generated indexes are disabled, the reference lab responds with 403 for that directory. An absent URL such as /withdrawn-meeting instead returns 404 with the prepared message.
Install the candidate only after reviewing its source and confirming the destination belongs to the fresh assigned exercise. The helper refuses any existing destination and checks the exact site mapping before activation. The administrative include directory must be reserved for trusted configuration authors. Ensure no other configuration change is in progress, and review the specific filename and destination to make the handoff reversible.
(
set -eu
candidate="$PWD/housing-board-lab.conf"
target=/etc/httpd/conf.d/housing-board-lab.conf
test -f "$candidate"
test ! -L "$candidate"
sudo sh -c '
set -euC
test ! -e "$2"
test ! -L "$2"
umask 022
cat "$1" > "$2"
' sh "$candidate" "$target"
sudo apachectl configtest
sudo httpd -S
)
Read the syntax result and the new vhost listing. If the candidate fails validation, remove or fix only the file installed by this step and test again before any activation. If the unit is inactive, start it for the lesson with sudo systemctl start httpd. If it is already active on your approved lab host and the planned change calls for applying the site, use sudo systemctl reload httpd. Check systemctl is-active httpd, inspect port 80 with ss, and read recent unit logs if startup reports a failure.
A graceful reload allows a supported Apache process to start handling new requests with the selected configuration while in-flight requests finish. Check how the installed unit implements reload before assuming its exact behaviour. Site-specific access and error logs help with request problems; the unit journal is also useful for activation failures because the process may exit before the site is involved. A successful syntax test still leaves questions such as which process owns the listener and what the virtual host actually returns.
Lab one: compare a directory with its readable file
Before running the checks, put the line “Housing board meeting calendar” into your homepage, the line “Retired notice or unknown path” into the 404 document, and the line “Public sample handout” into samples/handout.txt. Set the stylesheet to include a rule named .meeting-time and link it from the homepage. Use a root-relative link such as /css/notice.css. The fixture uses these lines as short content markers. Your documents can also contain complete HTML and useful accessibility labels.
Run this verification from the approved AL2023 guest when its listener accepts local traffic at port 80. Curl's address override connects to loopback and sends the practice hostname. For each path, the helper writes the body to one new disposable file, prints the status and MIME type, and displays a short relevant line if available. If you changed the release markers, change only the comparison text. The script deliberately considers a 404 and a 403 proper HTTP responses and leaves their interpretation to your evidence table.
(
set -eu
name=housing-board.example.test
body=$(mktemp "${TMPDIR:-/tmp}/housing-http.XXXXXX")
trap 'rm -f -- "$body"' EXIT
get() {
printf '\nRequest %s\n' "$1"
curl --noproxy '*' --resolve "$name:80:127.0.0.1" \
--silent --show-error --max-time 6 --output "$body" \
--write-out '%{http_code} %{content_type}\n' "http://$name$1"
}
get /
grep -F 'Housing board meeting calendar' "$body"
get /css/notice.css
grep -F '.meeting-time' "$body"
get /samples/
get /samples/handout.txt
grep -F 'Public sample handout' "$body"
get /withdrawn-meeting
grep -F 'Retired notice or unknown path' "$body"
)
| URL path | Expected status | Useful body evidence |
|---|---|---|
/ | 200 | The association's meeting calendar marker. |
/css/notice.css | 200 | A text/css response and the CSS class for the notice. |
/samples/ | 403 | No generated list of files from that directory. |
/samples/handout.txt | 200 | The text in the ordinary readable handout. |
/withdrawn-meeting | 404 | The custom missing-resource notice. |
Keep all five results. The 403 tests a directory that exists but lacks the required index. The 404 tests a missing URL. The exact handout path proves that the response for the directory did not remove authorization to the file. If the samples/ request instead displays an index page, confirm whether an index filename was present or the options were overridden. If the handout gets 403 as well, inspect the site's authorization, the filesystem path, parent traversal and host policy before concluding that Apache's directory listing rules caused both.
sudo tail -n 12 /var/log/httpd/housing-board-lab.access.log
sudo tail -n 12 /var/log/httpd/housing-board-lab.error.log
sudo journalctl -u httpd --no-pager -n 15
Check the per-site access entries by time and path. The access log can show you that an HTTP exchange happened even when the browser reported only a blank page. An error log may show whether a directory index was unavailable, authorization rejected the request, or a file path could not be read. The unit journal provides a different type of evidence when the service process itself cannot initialize. When there is no listener, fix that before interpreting the site's request logs.
Read the request line, response status, and error event together
Open the two records for the intentional missing-meeting request. An access log usually shows the request line, a time and the final response status, according to its format. A log format is the template that determines which fields appear and where. The reference fixture uses %r to record the original request line and %>s for the final status. The first field retains the missing URL even though Apache used the local /404.html body. This distinguishes the reader's action from the server's choice of error document.
The 403 entry for /samples/ gives a second row. Look for a contemporaneous message about an unavailable directory index and disabled directory listing if the package is logging those errors. The matching time and path help link the rows, especially if other trainees are generating traffic. No error entry is required for a successful handout. A request can be included in one log and intentionally absent in the other. Compare what each log is configured to record before treating silence as proof of a network failure.
When reporting an issue to the trainer, capture a recent timestamp and the exact path, status and relevant error line for your own request. Include which virtual host and client path you used. Avoid pasting an entire log because it can contain unrelated traffic, addresses and query values. Use reproducible synthetic request paths without secrets in the query. A brief diagnostic report has enough context for another student to repeat the same check and see the distinction between a missing resource and a policy refusal.
Lab two: test Apache rules with a disposable foreground process
This alternate exercise uses Python 3, an available Apache 2.4 binary, and its matching dynamic modules. The script checks the two common module locations used by this sample on macOS and RPM-based Linux, and accepts an approved binary through HTTPD_BIN and a matching module directory through HTTPD_MODULE_DIR. Run it as an ordinary user. It creates its own root, runtime directory and log files, uses just a loopback socket, and checks the configuration before launching the private process. It exercises upstream Apache behaviour, independent of the package's normal service setup.
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
httpd = os.environ.get("HTTPD_BIN") or shutil.which("httpd")
mods = os.environ.get("HTTPD_MODULE_DIR")
if not mods:
dirs = ("/usr/libexec/apache2", "/usr/lib64/httpd/modules")
mods = next((d for d in dirs if Path(d, "mod_mpm_event.so").is_file()), "")
if not httpd or not mods or os.getuid() == 0:
raise SystemExit("Use an approved Apache binary and modules, without sudo.")
module_names = {
"mpm_event": "mpm_event",
"unixd": "unixd",
"authz_core": "authz_core",
"dir": "dir",
"mime": "mime",
"autoindex": "autoindex",
"log_config": "log_config",
}
builtins = subprocess.run([httpd, "-l"], text=True,
capture_output=True, check=True).stdout
lines = []
for module, filename in module_names.items():
if f"mod_{filename}.c" in builtins:
continue
path = Path(mods) / f"mod_{filename}.so"
if not path.is_file():
raise SystemExit(f"Matching module unavailable: {path}")
lines.append(f'LoadModule {module}_module "{path}"')
with TemporaryDirectory(prefix="housing-httpd-") as temp:
base = Path(temp)
root = base / "sample"
(root / "samples").mkdir(parents=True)
(root / "css").mkdir()
(root / "index.html").write_text("Housing board meeting calendar\n")
(root / "404.html").write_text("Retired notice or unknown path\n")
(root / "samples/handout.txt").write_text("Public sample handout\n")
(root / "css/notice.css").write_text(".meeting-time { color: teal; }\n")
(base / "mime.types").write_text("text/html html\ntext/plain txt\ntext/css css\n")
with socket.socket() as probe:
probe.bind(("127.0.0.1", 0))
port = probe.getsockname()[1]
config = base / "httpd.conf"
name = "housing-board.example.test"
config.write_text("\n".join(lines) + f"""
ServerRoot "{base}"
DefaultRuntimeDir "{base}"
PidFile "{base / 'httpd.pid'}"
Listen 127.0.0.1:{port}
ServerName {name}
ErrorLog "{base / 'startup.log'}"
TypesConfig "{base / 'mime.types'}"
<Directory "/">
Require all denied
</Directory>
<VirtualHost 127.0.0.1:{port}>
ServerName {name}
DocumentRoot "{root}"
<Directory "{root}">
Options None
AllowOverride None
AllowOverrideList None
Require all granted
DirectoryIndex disabled
DirectoryIndex index.html
</Directory>
ErrorDocument 404 /404.html
ErrorLog "{base / 'site.error.log'}"
CustomLog "{base / 'site.access.log'}" "%r %>s"
</VirtualHost>
""")
args = [httpd, "-f", str(config)]
subprocess.run([*args, "-t"], check=True)
process = subprocess.Popen([*args, "-DFOREGROUND"])
try:
for attempt in range(60):
if process.poll() is not None:
raise RuntimeError((base / "startup.log").read_text())
with socket.socket() as conn:
if conn.connect_ex(("127.0.0.1", port)) == 0:
break
time.sleep(0.05)
else:
raise RuntimeError("Local Apache listener did not start.")
checks = (
("/", 200, "text/html", "Housing board meeting calendar"),
("/css/notice.css", 200, "text/css", ".meeting-time"),
("/samples/", 403, "text/html", ""),
("/samples/handout.txt", 200, "text/plain", "Public sample handout"),
("/withdrawn-meeting", 404, "text/html", "Retired notice or unknown path"),
)
for path, status, content_type, marker in checks:
conn = HTTPConnection("127.0.0.1", port, timeout=4)
try:
conn.request("GET", path, headers={"Host": name})
response = conn.getresponse()
body = response.read().decode("utf-8", errors="replace")
assert response.status == status, (path, response.status)
assert response.getheader("Content-Type").startswith(content_type), path
if marker:
assert marker in body, path
print(f"{status} {path}")
finally:
conn.close()
log = (base / "site.access.log").read_text()
assert "GET /samples/ HTTP/1.1 403" in log
assert "GET /withdrawn-meeting HTTP/1.1 404" in log
finally:
process.terminate()
try:
process.wait(timeout=8)
except subprocess.TimeoutExpired:
process.kill()
process.wait()
PY
Read the two neighbouring lines from the directory test. A request to /samples/ should report 403. Adding handout.txt should produce 200. Apache has made a separate decision for the directory and for the named file. The 404 check demonstrates that an ordinary local error resource can provide friendly text and keep a failure status. The shell exits after Python stops the child process and deletes the contents of its temporary directory.
Use the exact version of modules built for the selected Apache executable. Loading modules from a different operating system or Apache build can raise a loader or module compatibility error. Missing modules are a scope check for the fixture. This example assumes dynamically loaded components or the named compiled-in equivalents and need not fit every custom build. A listener bind error can also occur if another process takes the short-lived reserved address between port discovery and launch. Run the fixture again for a new local port. The new configuration's paths point only at the temporary tree, so fixing the exercise never requires replacing the machine's service configuration.
Explain a 403 without guessing at permissions
HTTP status 403 means the server understood an HTTP request and refused to fulfil it. In this exercise Apache gives 403 when you ask it to present a directory without an index and it is not allowed to generate a listing. Another setup can give the same status because authorization denies the client or the server cannot read the file. A browser can also give its own security message about a resource. Compare the raw HTTP response and the server log before applying any permission fix.
On AL2023, check the resolved root and all ancestors, and determine the worker identity from the effective configuration or the running service. The manager process can begin with administrative privileges and worker processes have their own runtime credentials. Avoid using sudo cat as proof that the worker can read a page. That command establishes that a privileged caller can access those bytes. A successful request through the intended vhost and the expected worker log gives evidence from the correct context.
ROOT=/var/www/housing-board-lab
ls -ld "$ROOT" "$ROOT/samples"
namei -l "$ROOT/samples/handout.txt"
ps -eo user,pid,ppid,comm | grep '[h]ttpd'
On a host that enforces SELinux, a file can appear readable by ordinary permissions while a policy decision prevents the web process from opening it. On AL2023 inspect the host configuration rather than assuming every image enforces an identical policy. If the guest reports an access denial, have an administrator interpret the scoped policy evidence and context for that site. When the site config turned off directory lists deliberately, opening the permissions further would be unrelated to the cause. The direct handout request and directory error entry are the smallest useful pair of checks.
Also inspect the route's exact final slash. A request for a real directory without its trailing slash can be redirected to the slash form by Apache. That redirect allows child links to resolve beneath the directory correctly. If you ask for /samples during a troubleshooting session you may first see a 3xx, then a 403 after following the redirect. Record both responses and compare the same two requests consistently. A redirection status alone does not tell you what the final target returns.
Plan how to expose the result and remove the practice files
A loopback response can be enough to demonstrate Apache's behaviour. To verify externally on a permitted training host, check the approved EC2 destination and path, then make the same test with the intended hostname. A security group or guest firewall controls who reaches the listener. The virtual host and directory settings control the response once the request arrives. An existing HTTP 403 from your site's log provides evidence that the specific request reached Apache. A connection timeout without any site entry suggests you should first verify destination, socket, routing and network controls for that path.
The absence of directory listing is a display rule. It does not replace a content approval process. For a real association, review every public path in a staging manifest, including copied spreadsheet exports, older rate sheets and hidden editor files. Keep historical releases in a separate private location. A web publisher who wants a public archive should choose deliberate archive filenames and links. Leaving old files in the served tree because they are hard to guess gives clients a potential way to reach them directly.
After the exercise compare the package and activation states with those you recorded. If you added only a unique site conf, remove or archive that exact file away from active includes. Run apachectl configtest again and use the authorized activation method. Confirm the former practice host is absent from the virtual host map. Keep the old fallback in mind. After removing a vhost, an old browser link may reach a different default, so absence from the map is stronger evidence of removal than any one browser status.
When the lab owner approves removal, delete only the disposable published tree and synthetic content created for this exercise. Keep its log data under the agreed retention rules. If the trainer assigned a free machine only for this run, follow the stated shutdown and resource cleanup procedure. An EC2 instance, a reserved address and a separate storage volume can have different lifetimes. Record which resources were yours before changing their state. A neighboring site's configuration and active service can continue unaffected because the exercise was isolated from the start.
Ask someone else to verify the handoff from a clean client
Give the secretary a small acceptance report with the assigned host, the date marker in the schedule and the expected missing page behaviour. Have a second learner open the site with a fresh client and perform the known-path checks. A direct request for the stylesheet helps them recognize when the path has changed or the type is unexpected. The network route and instance address may be different from the original administrator's shell. Check that this client reaches the actual approved endpoint rather than silently connecting to a previous association site.
During a scheduled update, keep the previous public set outside the active tree. Record its exact filename and release markers alongside those of the new version. If the meeting has the wrong date, choose the approved previous release and recheck the three most important paths before closing the incident: homepage, schedule, and old meeting URL. The last one can accidentally inherit a rule that routes it to an outdated replacement. Recovery is the return of identifiable behaviour, shown by a request with the expected body and status.
If the association has only a local practice endpoint, record that the verification covered loopback and the virtual host policy. External reachability and HTTPS belong to a later planned check. A report saying “Apache returned the intended public sample at these five paths from this client” is a clear finding. It lets the owner decide which additional network or certificate evidence the release needs without interpreting a screenshot as a complete deployment test.
Interview questions with explained answers
Can a VirtualHost statement open a new listening port?
No. The socket is controlled by Apache's listening configuration. The virtual host port identifies which requests are eligible for the block. Inspect both the configured Listen directives and the operating system listener when troubleshooting.
Why can an index-less directory and its text file return different statuses?
Presenting the directory as a page needs a configured index or permission to generate a listing. With neither available, the directory request can receive 403. A request for the known text file only needs its own mapping, authorization and file read. That can succeed independently.
Will AllowOverride None switch off Apache's main configuration?
It changes how Apache handles per-directory override files in the selected scope. The directives in the main and included site configuration still apply. For a static site controlled by the administrator, those directives can define the complete root policy.
How do you decide where a typo in ServerName took effect?
Inspect the vhost mapping to see which name and source file were parsed. Request the intended hostname through the exact listener, and then match the access log. When no name matches, the default for the eligible address and port group can answer.
What evidence distinguishes a static site from a database connection problem?
Here Apache reads named HTML and CSS files and sends their bytes directly. There is no application query as part of that request. A missing file or incorrect site mapping should be investigated in the HTTP server's configuration and filesystem. A separate dynamic site would add application and database evidence.
Check your understanding
The port 80 listener is an Nginx process serving another class. Which version of this lesson can you run?
Show answer
Use the independent loopback process with an unprivileged port, or obtain a separate assigned host. The Nginx sites can continue serving while you learn Apache's file and directory rules.
The
samples/directory returns 403 andsamples/handout.txtreturns 200. Which setting explains the difference?Show answer
The directory has no index and generated listings are off. The known ordinary file is authorized and readable. The pair is consistent with the intended directory policy.
A custom error document redirects to a different hostname after a missing request. Which configuration detail matters?
Show answer
A complete external error URL leads to a redirect. Use a local URI path and check both the expected error status and its body for the site's exercise.
Why compare
httpd -Swith an HTTP request?Show answer
The first shows configured virtual host definitions and ordering. A request verifies the process and listener reached by the client actually selected the intended site and returned its content.
Can you keep a private spreadsheet beneath the public document root by omitting its link?
Show answer
The public file can still be reachable through its direct path. Keep private work outside the public release and give it an explicit approved access policy.
Practise with the association release
Write a five-row test report for the root, CSS, empty-index directory, exact handout and missing notice. Include an expected status and one useful piece of evidence per row.
In the isolated fixture, add a harmless
samples/index.htmlfile. Predict whether/samples/still returns 403. Adapt that one assertion to check your prediction and explain how the directory rule found the new index.Explain what changes when you test
/sampleswith and without curl's redirect-following option. List the first response and the response that represents the directory's own policy.
Revision cards
httpdon AL2023- The Apache RPM package and managed unit. Confirm the guest OS before applying a different distribution's commands.
- Listener and virtual host
- The listener accepts a connection. The vhost identifies settings for names and requests associated with that address and port.
- Document root and directory rule
- One anchors file lookup. The scoped directory block tells Apache which behaviours and access rules apply there.
DirectoryIndex- The file Apache looks for when responding to a directory URL. A missing index and disabled directory listing can lead to 403.
AllowOverride None- Put the sample's configuration policy in administrator-managed files instead of relying on per-directory override files.
- Local error document
- A path used to render the error body for the site's response. A separately requested external URL has different behaviour.
Official sources
- Amazon Linux 2023 Apache package and service
- Amazon Linux package manager
- SELinux in Amazon Linux 2023
- Apache virtual host matching
- Apache listener addresses and ports
- Apache core directives
- Apache DirectoryIndex and slash behaviour
- Apache directory listings
- Apache authorization directives
- Apache access logging directives
- Apache runtime and configuration checks
- Apache reload and shutdown mechanics
- systemctl unit and service reload
- Curl command options and redirects
- HTTP semantics
- DNS reserved test names