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

Chapter 8: Configuring Nginx and Apache

AWS Cloud

8.4 Reading an Apache configuration

Friends, Apache has no semicolons – one directive, one line. And sections like <VirtualHost> and <Directory> sit in angle brackets. If you understood Nginx, this will feel very familiar.

Apache uses directives (one per logical line, with a backslash for continuation) and sections in angle brackets:

# /etc/httpd/conf.d/mysite.conf   (Ubuntu: /etc/apache2/sites-available/mysite.conf)
<VirtualHost *:80>
    ServerName  example.com
    ServerAlias www.example.com
    ServerAdmin webmaster@example.com

    DocumentRoot /var/www/mysite
    DirectoryIndex index.html

    <Directory /var/www/mysite>
        Options -Indexes
        AllowOverride None
        Require all granted
    </Directory>

    ErrorDocument 404 /404.html
    ErrorLog  /var/log/httpd/mysite_error.log
    CustomLog /var/log/httpd/mysite_access.log combined
</VirtualHost>

Use the log paths appropriate to your installation. The usual Ubuntu service wrapper supplies ${APACHE_LOG_DIR}. The sample also assumes your configuration defines the log format nickname combined.

Directive What it does
<VirtualHost *:​80> A virtual-host definition eligible for port 80. The listener itself is configured by Listen.
ServerName / ServerAlias Main host name / extra names for this site
DocumentRoot Starting directory for the usual static URL-to-file mapping
DirectoryIndex File served for a folder request
<Directory path> Rules for a folder on disk
Options -Indexes Disable automatic folder listing
AllowOverride None Disables override categories for this managed static configuration. Delegated applications can use explicitly selected directives when needed.
Require all granted Grant authorization in this scope. The process still needs operating-system access.
ErrorLog / CustomLog Per-site log files
Listen Address and port, or only port, on which Apache accepts connections. The file depends on the installed configuration.
ServerTokens Prod + ServerSignature Off Reduce version details in the Server header and generated page signatures. Set ServerTokens in server-wide scope.

No inline comments in Apache

Require all granted # allow all is an error in Apache. Comments must be on their own line starting with #.

How Apache chooses the virtual host

Apache first finds the most specific applicable virtual-host address and port, then compares the requested name against eligible ServerName and ServerAlias values. If no name matches in that group, the first eligible virtual host is the fallback. Wildcard include patterns can load files alphabetically, but overall declaration order depends on the include chain. Use your service's Apache wrapper with -S to inspect the candidate host order.

*:80   is a NameVirtualHost
       default server example.com (/etc/httpd/conf.d/mysite.conf:1)
       port 80 namevhost example.com (/etc/httpd/conf.d/mysite.conf:1)
               alias www.example.com

Ravindra Bagale's Tip

Opening the server by IP can select the default because the request carries a different name. Use the same startup settings and -S report to identify the first eligible virtual host. Test the intended hostname separately.

Lab

Chala, tumcha Apache vhost ughda aani DocumentRoot, <Directory>, Require all granted aani ErrorLog chya lines olakha. Mag sudo apachectl -S chalva aani default server kontya file madhun yeto te liha.

Read the site selection, file mapping and access policy separately

Picture a small training center that serves a workshop and a library from the same Apache HTTP Server installation. Students reach the workshop by name and receive the correct homepage. A link to an empty notes folder returns 403. Another link to an absent PDF returns a branded error page. Pasting the server's address into a browser displays the library. Each outcome is compatible with a running, syntactically valid server. The first question is which site Apache selected. The next question is how the request maps to a resource. After that, ask whether the matching rules allow the request and what happens if the resource cannot be served.

Apache HTTP Server, also called Apache or httpd in this chapter, reads instructions written in configuration files. A directive is an instruction with a name and usually one or more arguments. A simple Apache directive normally occupies one logical line. If a line ends in a continuation backslash with no characters after it, the next physical line is part of the same logical line. Apache directives do not use Nginx's terminating semicolon. The configuration accepts comment lines starting with a hash. Keep comments on their own lines; inline comments on directive lines are not supported. A Windows path or quoted string has its own syntax concerns, so check the actual form before adapting an example.

A configuration section encloses other instructions and indicates when or where they apply. Angle brackets mark its opening and closing lines. The virtual-host section identifies a candidate site on one or more addresses and ports. A Directory section matches a filesystem directory and ordinarily includes its descendants. A Files section matches filenames. A Location section matches a URL space rather than a filesystem directory. These sections can overlap, and Apache combines their directives according to section ordering and module-specific rules. Begin with a small config where you can name which sections apply without assuming the last line printed on screen simply wins.

A module is a part of Apache implementing a particular set of capabilities. The core provides basic features, and loaded modules supply additional directives and behavior. For example, mod_dir supplies DirectoryIndex and slash redirection. The authorization module provides Require rules. A config may parse on one package but reject a directive on another host because a supporting module is absent. A condition around a module only determines whether text is read inside that condition. It does not install the missing capability. Confirm the module list for the same binary and startup options when a rule seems unavailable.

Start from the entry file identified in the configuration discovery lesson. The main configuration can include site files, module configuration, and connection settings. Look at context wherever the include is read. If a line belongs to a specific site, its file name is secondary to where the opening and closing virtual-host section marks actually are. Use parsed host reports to support your reading, then use a request to check the actual behavior. Reading a config is a trace over the real route, not a list of every directive the package supports.

Follow the listener and the virtual-host order

A listener is the address and port on which a process accepts connections. Apache's Listen directive binds an address and port, or a port over suitable interfaces when no address is written. A VirtualHost section describes settings eligible for connection destinations that match that section. It does not cause Apache to open a socket. Suppose a site block declares an endpoint on 18884 and Apache listens only on 80. A browser trying 18884 will find no listener there merely because a virtual-host definition names it. The reverse is also possible. An endpoint can accept traffic before the virtual hosting rules users expect are configured.

For a small name-based configuration, Apache identifies the best matching virtual-host address and port, then compares the supplied name to the eligible ServerName and ServerAlias declarations. The primary server name is the principal name associated with that definition. An alias supplies another name that maps to the same definition. Alias is an overloaded word here: ServerAlias concerns incoming site names. The Alias directive from mod_alias maps a URL prefix to a disk location. One common mistake is to reason about the second while debugging a first-stage name mismatch.

On the shared lab listener, library.test is declared first and workshop.test is declared second. Both use 127.0.0.1 and port 18884. The name teacher.test is a ServerAlias declared with workshop. A request for workshop.test or teacher.test selects the workshop definition. A request for an unrecognized name falls back to the first virtual host for that eligible address and port. In an ordinary wildcard include, alphabetical filename order can determine which definitions are read first. It does not override an explicit earlier include elsewhere in the parsed input. Use the parsed host report instead of inferring ordering from a single directory listing.

Imagine a third named definition with a wildcard address and a fourth with the exact local address. Apache's address and port matching has its own precedence. A trainer might see a hostname in the wildcard-host group that seems perfect, while the connection is already assigned to a better address match. Begin with the address match and inspect the name group that actually applies to it. Keep all definitions in the same simple address group when learning name matching. Later, add an exact address or a new port only as a single controlled change.

The main server consists of settings outside virtual-host declarations. It is distinct from the first virtual host in a matching name group. A response from an unknown name can come from that first eligible virtual host rather than the main server's document directory. In the lab the independent library deliberately serves the fallback marker. That makes a diagnostic point. A successful status received by IP alone can still come from the wrong site. Test the intended address and port with the intended hostname so the observation refers to the configuration you are reviewing.

A plain HTTP request to a name normally carries that name in the Host header. For a local controlled request, curl can override address resolution for one hostname and port while keeping the host in the URL. In HTTPS the name is also relevant at the TLS stage. Keeping it in the URL allows a client to request and check the intended certificate while using a controlled destination, when that route is appropriate. An HTTP-only training listener does not exercise certificate selection. Document the protocol and effective local or public route separately so a 200 from one cannot be mistaken for verification of the other.

Work through Apache filesystem and URL scopes

After you identify the virtual host, look for the relevant mapping. The DocumentRoot is the base directory from which an ordinary static request is served. If the workshop declares /srv/training/workshop and the request is for /notes/intro.txt, the ordinary candidate is /srv/training/workshop/notes/intro.txt. An application handler, an alias or a rewrite can change how that path is resolved. A Directory section grants settings for the disk path. It does not choose the public hostname or create an alias. For a move to a new DocumentRoot, inspect the corresponding access rules for the new disk path. The next lesson practices that exact migration.

When looking at access, a successful mapping is only one step. Apache's authorization rules must allow the request, and the worker must be able to traverse and read the target under the operating system's permissions and security policy. A broad denial for the filesystem can be paired with an explicit grant for a small public directory. Later, narrower rules can keep a reserved filename unavailable inside that directory. A site whose homepage opens therefore gives no promise that every matched file may be downloaded. The lab uses harmless marker files to verify the difference between a path that maps but is denied and a path that is simply missing.

A Files section is helpful when a particular filename needs a rule wherever it could appear under the relevant scope. A Location section can apply policy to a URL independently of the exact file path or handler Apache will use. Be deliberate when configuring both. For example, a URL-based authorization grant can override an earlier filesystem restriction in some configurations. Read the merge rules supplied by the server and modules before adding overlapping authorization. This lesson uses a small, intended denial at each level. It confirms both with controlled responses rather than making claims about every combination of settings.

The access control files named .htaccess enable delegated directory configuration when permitted by the server. If you administer the main configuration, keeping rules in that managed config with overrides disabled makes the scope simpler to audit. Some packages or hosted applications expect specific override categories. Enable only the directives the application requires, and document why. Setting AllowOverride All for every virtual host can make unseen files affect behavior. At startup a configtest can validate the central files without checking every override file that may be read later for a request. For a request-time error, inspect the effective override policy before assuming those files are irrelevant.

For directory URLs, DirectoryIndex lists filenames used as possible defaults when the relevant module handles the request. A request for /notes/ can be served by notes/index.html without changing the displayed URL. Apache may send a redirect to append a slash when the path names a directory and the slash is absent. Automatic directory listings are a separate feature. When no index is present and listing is disabled, the resulting denial is evidence about directory handling, even if a named file beneath that directory can be served. An index name ending in PHP does not execute PHP without another configured handler for that language.

Inputs that select a file, scope or response
InputRelevant scopeResult to check
Connection destination and host nameListen and matching VirtualHost groupWhether workshop, its alias or the fallback handled the request
A path to a normal public fileDocumentRoot plus matching filesystem sectionsComputed file, appropriate access and actual body
A reserved filenameApplicable Files sectionExpected access denial despite the file existing
A reserved URL pathApplicable Location sectionExpected denial for that URL regardless of its mapped file
A nonexistent assetMapping and configured ErrorDocumentExpected 404 and the site's chosen error body

An error document can provide a readable body for a failure without changing the fact that the request failed. A local URL configured for a 404 can trigger internal handling of a known custom page. If the error target is itself missing or denied, the final result can differ from the intended branded page. Apache's error logs and the actual HTTP response give clues about both paths. If the error target is an external address, the client can instead encounter a redirect. In this lab, verify the response status and short marker together so a generic server page cannot masquerade as the custom example.

Lab to read a live virtual host with controlled requests

Set aside a disposable practice machine with Bash, curl, and Apache HTTP Server 2.4 installed. Run this lab as a regular account. It creates temporary configuration and static markers, then starts one private Apache child on 127.0.0.1 port 18884. Do not modify system configuration, stop another service or allow public access to that port. If the port is already in use, change every reference in the lab to a different unused high port. The shell keeps track of the temporary directory and child for teardown. This exercise is also useful as a parser-only activity when you cannot start a private listener.

The first block picks the existing Apache executable and module directory. Nothing is installed as part of the example. The functions will later identify whether a module that the lab needs is linked into the executable or must be loaded from that directory. The collection may be named or installed differently in a custom build. Stop and inspect the package when you cannot verify its directory. In the usual package case, the modules support simple HTTP authorization, directory handling, process startup and log formatting.

if [ "$(id -u)" -eq 0 ]; then
  printf 'Use a regular practice account.\n' >&2
  exit 1
fi
apache_bin=$(command -v apache2 || command -v httpd) || exit 1
ap_lab=$(mktemp -d /tmp/rb-apache-reading.XXXXXX) || exit 1
lab_pid=
apache_read_cleanup() {
  if [ -n "$lab_pid" ] && kill -0 "$lab_pid" 2>/dev/null; then
    kill "$lab_pid"
    wait "$lab_pid" 2>/dev/null || :
  fi
  case "$ap_lab" in
    /tmp/rb-apache-reading.??????) rm -r -- "$ap_lab" ;;
  esac
}
trap apache_read_cleanup EXIT

module_dir=
for candidate in /usr/lib/apache2/modules /usr/lib64/httpd/modules /usr/lib/httpd/modules /usr/libexec/apache2; do
  if [ -r "$candidate/mod_dir.so" ] && [ -r "$candidate/mod_authz_core.so" ]; then
    module_dir=$candidate
    break
  fi
done
if [ -z "$module_dir" ]; then
  printf 'Locate the Apache package module directory before continuing.\n' >&2
  exit 1
fi
mkdir -p "$ap_lab/sites" "$ap_lab/logs" "$ap_lab/library" "$ap_lab/workshop/notes"
printf 'library-home\n' > "$ap_lab/library/index.html"
printf 'workshop-home\n' > "$ap_lab/workshop/index.html"
printf 'public-notes\n' > "$ap_lab/workshop/notes/guide.txt"
printf 'reserved-file-fixture\n' > "$ap_lab/workshop/_internal.txt"
printf 'reserved-url-fixture\n' > "$ap_lab/workshop/preview.txt"
printf 'workshop-missing-page\n' > "$ap_lab/workshop/missing.html"

Every content marker belongs to the generated public trees. The names of the reserved markers indicate which policy should deny each request, even though the files really exist on disk. The notes directory deliberately lacks an index while containing a readable direct file. This pair gives you a way to observe directory index denial separately from file access. The cleanup routine removes only the lab's generated directory and handles the child it owns. Leave the shell open until you have recorded the results.

Construct the entry config with a specific listener, separate runtime directory and a wildcard include. The files only have their relative ordering because that one rule picks them. The directory block for the root of the filesystem establishes a default denial, and the sites will explicitly permit their own public directories. A log format prints the canonical virtual-host name, URL path and final HTTP status. The workshop and library then write separate access logs. Read the output of the host and module reports before starting. The reports describe what this private candidate contains.

static_modules=$("$apache_bin" -l) || exit 1
module_line() {
  local identifier=$1 basename=$2
  if ! printf '%s\n' "$static_modules" | grep -Eq "(^|[[:space:]])mod_${basename}\.c$"; then
    test -r "$module_dir/mod_$basename.so" || return 1
    printf 'LoadModule %s_module "%s/mod_%s.so"\n' "$identifier" "$module_dir" "$basename"
  fi
}
{
  printf 'ServerRoot "%s"\n' "$ap_lab"
  if ! printf '%s\n' "$static_modules" | grep -Eq '(^|[[:space:]])(event|worker|prefork|mpm_event|mpm_worker|mpm_prefork)\.c$'; then
    module_line mpm_event mpm_event || exit 1
  fi
  module_line unixd unixd || exit 1
  module_line authz_core authz_core || exit 1
  module_line dir dir || exit 1
  module_line autoindex autoindex || exit 1
  module_line log_config log_config || exit 1
  cat <<APACHE
ServerName main.test
User "#$(id -u)"
Group "#$(id -g)"
DefaultRuntimeDir "$ap_lab"
Listen 127.0.0.1:18884
PidFile "$ap_lab/apache.pid"
ErrorLog "$ap_lab/logs/main-errors.log"
LogFormat "%v %U %>s" lesson
<Directory />
    AllowOverride None
    Require all denied
</Directory>
Include "$ap_lab/sites/*.conf"
APACHE
} > "$ap_lab/httpd.conf"
cat > "$ap_lab/sites/000-library.conf" <<APACHE
<VirtualHost 127.0.0.1:18884>
    ServerName library.test
    DocumentRoot "$ap_lab/library"
    DirectoryIndex index.html
    <Directory "$ap_lab/library">
        Options -Indexes
        Require all granted
    </Directory>
    ErrorLog "$ap_lab/logs/library-errors.log"
    CustomLog "$ap_lab/logs/library-access.log" lesson
</VirtualHost>
APACHE
cat > "$ap_lab/sites/010-workshop.conf" <<APACHE
<VirtualHost 127.0.0.1:18884>
    ServerName workshop.test
    ServerAlias teacher.test
    DocumentRoot "$ap_lab/workshop"
    DirectoryIndex index.html
    <Directory "$ap_lab/workshop">
        Options -Indexes
        Require all granted
        <Files "_internal.txt">
            Require all denied
        </Files>
    </Directory>
    <Location "/preview.txt">
        Require all denied
    </Location>
    ErrorDocument 404 /missing.html
    ErrorLog "$ap_lab/logs/workshop-errors.log"
    CustomLog "$ap_lab/logs/workshop-access.log" lesson
</VirtualHost>
APACHE
readcfg() {
  "$apache_bin" -f "$ap_lab/httpd.conf" "$@"
}
readcfg -t || exit 1
readcfg -S || exit 1
readcfg -M || exit 1

The host report should show the library as default for the private endpoint, then the workshop with the teacher alias. The module report should identify the directory and authorization modules among the others. A maintenance note ought to separate what an included definition says from how a request maps to it. The order here is the result of the one include. The workshop's directory section applies to its actual disk path, and the Location section applies to the URL regardless of how that resource would map. The server's main block would otherwise deny access. Within the specific public workshop path, the narrower filesystem rule allows access except for the reserved file rule.

Start only after passing those tests. The background child is the process your shell started using its private configuration. Check the private PID file against that child to establish its ownership. A failure here stops the exercise before any probes go to an unexpected program. If the config parses but the private socket cannot be opened, check for a port collision. Do not infer that the site's authorization policy is wrong when no private process actually started.

"$apache_bin" -f "$ap_lab/httpd.conf" -DFOREGROUND &
lab_pid=$!
for attempt in 1 2 3 4 5 6 7 8 9 10; do
  if [ -s "$ap_lab/apache.pid" ]; then break; fi
  if ! kill -0 "$lab_pid" 2>/dev/null; then break; fi
  sleep 0.2
done
if ! kill -0 "$lab_pid" 2>/dev/null ||
   [ ! -s "$ap_lab/apache.pid" ] ||
   [ "$(tr -d '[:space:]' < "$ap_lab/apache.pid")" != "$lab_pid" ]; then
  printf 'The private Apache listener did not start. Check the port and local logs.\n' >&2
  if [ -r "$ap_lab/logs/main-errors.log" ]; then
    tail -n 10 "$ap_lab/logs/main-errors.log" >&2
  fi
  exit 1
fi

For each probe, name the expected definition and reason about the response before reading curl's output. The function saves status and body in temporary files, prints the first status and any Location header, then shows the beginning of the body for a quick comparison. None of these probes follows redirects automatically. A named response must therefore be interpreted as the first reply for that URL. Inspect the logs as well, especially where a successful result comes from the fallback.

apache_probe() {
  local name=$1 path=$2 status
  status=$(curl --noproxy '*' --max-time 5 -sS --resolve "$name:18884:127.0.0.1" \
    -D "$ap_lab/probe.headers" -o "$ap_lab/probe.body" -w '%{http_code}' \
    "http://$name:18884$path") || return
  printf '%s %s HTTP %s\n' "$name" "$path" "$status"
  grep -i '^Location:' "$ap_lab/probe.headers" || :
  head -c 120 "$ap_lab/probe.body"
  printf '\n'
}
apache_probe workshop.test /
apache_probe teacher.test /
apache_probe unknown.test /
apache_probe workshop.test /notes/guide.txt
apache_probe workshop.test /notes
apache_probe workshop.test /notes/
apache_probe workshop.test /_internal.txt
apache_probe workshop.test /preview.txt
apache_probe workshop.test /never.txt
tail -n 10 "$ap_lab/logs/workshop-access.log"
tail -n 5 "$ap_lab/logs/library-access.log"

The workshop and teacher names should both produce the workshop marker. The unknown name should receive the library home because it reached the first virtual host. The workshop direct notes file is readable. The notes path without the slash should return a redirect to the slash form. The slash path enters the directory handling branch, has no index and cannot fall back to a listing, yielding 403. The reserved file and reserved URL each return 403 for different scoped reasons. The final absent file returns 404 with the configured workshop marker. This gives you two 200 bodies, a redirect, several reasons for 403, and a site-specific 404 in a single run.

The workshop access log uses the configured canonical name even when teacher.test was the incoming alias. The log's purpose is to tell you which virtual host performed the work, not to reproduce its input authority. The library log independently records the unmatched-name request because it reached the default. A requested name and the definition that answered can differ. For a production investigation with shared logs, review whether your configured fields capture both safely. Access logs may omit details you need, while error logs can give the specific reason for a failed lookup or access decision.

apache_read_cleanup
trap - EXIT
test ! -e "$ap_lab" && printf 'Private Apache lab removed.\n'

Before teardown, save your response table if this is a class submission. Include the input hostname, path, status, marker or redirect and reason linked to a real directive. Then end the lab process and verify its scratch directory is gone. The deployment method on a system-managed server differs from this disposable child. The private setup is intentional so you can test grammar and the actual request path without introducing a configuration change to another site.

Trace a published pathname that sits outside the site root

Suppose a training coordinator keeps a common set of blank forms in a shared directory. They want the same signup file available from workshop and library without copying it into two separate document directories. Keep two earlier concepts distinct. The hostname teacher.test reaches the workshop because it is another virtual host name. A path mapping for forms is separate. The mod_alias Alias directive could attach the shared file collection to a particular URL prefix. Its actual placement in the server or virtual host configuration determines which sites can use it. This example is a reading exercise. The private lab above leaves the alias directive out so you see the site-name alias in isolation.

# Illustrative lines inside the intended virtual host.
Alias "/forms/" "/srv/training/shared-forms/"
<Directory "/srv/training/shared-forms">
    AllowOverride None
    Options -Indexes
    Require all granted
</Directory>

Walk a proposed GET for the workshop signup file through that example. Apache matches the workshop host and the forms URL prefix. The file named signup.txt is looked up in the shared forms directory, independently of the workshop's main document root. The Directory section governs that physical location. If the server had only granted access to the workshop's normal root, the mapped file may fail authorization because it lives under a different path. The shared directory also needs to be traversable and readable according to its host policy. Supplying a URL name does not grant those permissions. A good before-and-after test would keep the main workshop homepage separate from the new form URL.

The proposed location ends in a slash, so include that suffix when testing the directory prefix and then request the actual filename. Apache's mapping can be sensitive to trailing-slash choices. Use ordinary file-only markers and avoid symlink assumptions while establishing the first result. Compare an existing form, a neighboring missing filename and a public file outside the forms prefix. If the old website already handled the same prefix in an application, read the relevant mapping and handler context before deciding which rule should now own it. A working dedicated hostname tells you nothing about how two candidate URI mappings will interact.

Ask what should happen if the same URL is requested with the library hostname. If the alias is declared only inside workshop, its scope ends when Apache chooses the library. If the rule is shared through a broader context or separately written in both sites, both can serve the same file by design. Before choosing the broader placement, identify whose public content will become reachable and which backup or source file manages it. With a shared directory, restoration of the site configuration and restoration of the folder are separate operations. A small access log and a unique form marker help identify whose requests actually used that path.

To confirm the lesson without configuring any shared filesystem directory, draw three rows on paper. In the first, teacher.test requests the workshop home and is selected by its name alias. In the second, workshop.test requests the signup form and uses the independent path alias. In the third, the workshop requests an ordinary notes file under its normal root. For each row explain which setting selects the site, which setting computes the resource path and whether a Directory rule would apply. The result shows why hostname alias, URL alias and disk policy are three distinct decisions.

Interpret a working listener with a failing route

A configuration failure and a request failure leave different evidence. If Apache reports a syntax problem before starting, look at the file, line and directive named by the parser. It can be an unrecognized directive due to a missing module, a context error because a directive was placed in the wrong section, or simply an argument that is misspelled. If an authorized real service was still running with earlier instructions, a failed candidate parse does not prove that its previous worker processes stopped. Check the current service state separately. In the private lab the host and module commands read the current candidate and can complete without binding an HTTP socket.

To practice recognizing a parser failure while retaining a working instance, keep the lab running and make a separate copy of the entry file in the temporary root. Add a directive with an inline comment to that copy using the following block. Then pass the bad copy explicitly to the syntax checker. The live entry and included site files remain the same. Do this before the cleanup block on a fresh run, or use the parser-only setup if you do not need live response evidence.

cp "$ap_lab/httpd.conf" "$ap_lab/invalid.conf" || exit 1
printf 'ServerName spare.test # copied from an inline note\n' >> "$ap_lab/invalid.conf"
if "$apache_bin" -f "$ap_lab/invalid.conf" -t; then
  printf 'Unexpectedly accepted the invalid example. Check the executable.\n' >&2
  exit 1
fi
readcfg -t || exit 1

The bad copy should be rejected because this directive is receiving additional tokens rather than a supported comment. The known good entry should still report successful syntax. No service activation was attempted. A parser error for one file and success for another are perfectly consistent. If the lab remains running, repeat one workshop probe and compare its marker with the earlier result. This takes the mystery out of an everyday experience where a configuration check appears to fail on one terminal while the site looks healthy on another.

Consider a 403 with no editing involved. The lab gives three reliable reasons for the same status. The request for an indexless folder denies listing. The reserved physical file is specifically denied in a Files section. The preview route is denied by a Location rule. If you change directory permissions because all three return 403, you may only change operating-system access while leaving the actual decision untouched. Read where the request ended, then inspect the server's configured access rule and error log for the particular path. The right resolution should match the intended policy, whether that is supplying a proper index, retaining a denial or changing a documented authorization requirement.

The notes path without a slash supplies another useful observation. The redirect Location header can reveal that Apache interpreted the URI as a directory and is sending the client to its slash form. That first 301 response does not guarantee the target folder will return a page. In the fixture, the next request arrives at an empty-index directory with listing disabled and gets 403. Test both initial and resulting URLs when diagnosing a report such as “the browser goes somewhere else and then fails.” Record which response belonged to which request, because a browser normally follows redirects without displaying the original hop.

The ErrorDocument case shows why body and status should both be inspected. Searching for the words workshop missing page in the HTML proves there is a custom body. The HTTP 404 status still matters to tools, browser navigation, cache behavior, and application decisions. An alternate external URL could send a redirect instead of a local error response. If one custom error target appears for both sites unexpectedly, check whether the directive was global or site-specific, and whether a reverse proxy supplied its own error handling before Apache saw the request. The live counterexample also helps you avoid reading a branded page as proof that the server found the requested asset.

In the local exercises, response logs can show /index.html for a client request made to the root slash. The logged URI field reflects request processing and is not necessarily the raw line originally sent by curl. A browser also might have requested several assets around the same time. Preserve your probe input alongside the log and decide which fields you need before changing the log format. Apache can log a request line, final status and configured server name if those fields are appropriate. A production request line or query can contain private values. Keep request logging proportionate to the investigation.

When several configuration containers seem to match, read the effective policy in the correct order. For ordinary filesystem sections Apache processes matching directory scopes in the documented order, then matches file and URL containers at their stages. The specific module's rule controls how its instructions are combined. An authorization block may replace an earlier result or combine with it according to its merge settings. Choose a single public directory for this lesson to keep the main chain visible. Review shared policy before adding a broader grant in a more specific-looking section, especially a URL-based grant that could bypass a reserved-file restriction.

Make a configuration reading worksheet

Use an approved practice file and annotate it with five columns. The first is the part of the request it cares about, such as local address, incoming site name, URL space, filename or disk directory. The second is the directive or section name. The third is the file and context that provides it. The fourth is the expected runtime observation. The fifth is the smallest useful probe to distinguish that result from other candidates. For a site selected by host, a meaningful contrast is an unmatched host on the same listener. For a filesystem versus URL rule, contrast an allowed sibling file with the forbidden fixture while staying on the same named site.

Then trace a fresh case from the worksheet. A workshop member says they can reach the site by domain, but their colleague's typed IP address “goes to a different server.” Both get a successful response. The listener table shows one matching endpoint, and the virtual-host report shows the library first. A probe preserving the domain makes the workshop marker return. Tell your partner whether they have evidence for different machines. An appropriate explanation is that both requests can be handled by the same process while different destination authority values select different virtual hosts. The body and per-site logs confirm the two choices without a claim about public DNS beyond the tested endpoint.

For a deeper practice task, predict an independent effect of changing one setting. Suppose the owner wants to supply a notes index to replace the directory denial. Leave the authorization and listing rules in place and add a synthetic index file to the lab notes directory. Predict that the slash-terminated URL can now serve the index and that the direct public notes file will remain readable. Predict that the reserved file and URL will still be denied. The tutorial's virtual-host settings should still route the teacher alias to workshop. By naming changes and non-effects before the probe, you ensure that a desirable new result cannot hide a broken neighboring path.

One remaining skill is translating from a package's layout to Apache's instructions. Ubuntu can use a wrapper supplying log directory variables and an enabled site directory. A distribution such as Amazon Linux often supplies the usual httpd package layout with an include for site or module configuration under its own directories. An upstream or container image can use another entry and module set. All three can express the same name, filesystem and URL policies. Work from the parser's evidence on the actual machine. Remember that a copied example containing a package variable will need the startup environment that defines it.

Finally, put the scope of a parser-only test in the worksheet. A syntax check ensures that one invocation accepted its current configuration. A module report helps identify whether the pieces needed by a directive were loaded. A virtual-host report displays the candidate grouping and defaults. None of those reads the permissions of every possibly requested file at runtime or demonstrates that an external client reaches this host. A file marked correct in the worksheet should have both its intended interpretation and observed request behavior wherever that check was available. Tell the next person which test to perform when only part of the evidence was collected.

Interview questions, quiz and revision cards

What is the difference between Listen and VirtualHost?

Listen opens an endpoint. VirtualHost defines a site that can be selected for an eligible address and port. Merely declaring a virtual host on another port does not open it. Check listeners first when a request cannot connect.

Can the first site be returned even when its hostname was never requested?

Yes. When Apache selected an address and port with a name-based group but found no eligible name match, its first virtual host can be the fallback. An explicit address and port match matters first. Consult the parsed host order and test a known host against the same endpoint.

What separates Directory and Location sections?

Directory describes policy for paths in the filesystem. Location describes policy for a URL space and can apply to locations with no corresponding local file. If both affect a request, read the section and module merge rules. The lab's reserved URI is denied by Location even though the underlying directory lets students read ordinary public files.

Why is relative include order important for the default?

The first definition for a name-based group is the usual fallback. A wildcard include can contribute files in alphabetical order, but a separate explicitly included file can precede the wildcard. The parsed virtual host report is the evidence to use for the particular candidate.

When does changing DirectoryIndex fix a 403?

It can help if a folder has no usable index and automatic listing is off. It does not fix a filesystem or URL authorization denial. Compare a direct allowed file in the same folder, inspect the directory and distinguish missing index from access policy.

What do you check if a packaged Apache directive is unknown on another host?

Confirm the syntax and allowed section in that version's documentation, then check modules for the exact candidate. A custom file or different installed module set can produce a different result even when the Apache service is already installed and running.

Quick quiz

  1. Workshop and teacher open the same page, while unknown.test displays the library on the same address. Which explanation fits the configuration?

    1. Workshop and teacher share a virtual-host definition, and the first eligible library is the fallback
    2. Each address necessarily runs a separate Apache binary
    3. Every hostname uses the main server's DocumentRoot
    Check the first answer

    A. The alias selects workshop, and an unmatched name uses the first virtual host on this shared listener.

  2. The slash version of the notes directory returns 403, while its direct guide is readable. What do you inspect first?

    1. Whether the hostname disappeared from DNS
    2. The directory index candidates and listing setting
    3. Whether Apache supports HTTPS
    Check the second answer

    B. The working child file shows the selected site and directory are reachable for that request. The indexless folder needs its own directory handling explanation.

  3. The absent workshop file returns the custom marker but still has status 404. Is that result expected?

    1. Only an external redirect can display a custom body
    2. A custom page always converts the response to 200
    3. A local custom error document can supply the body while retaining 404
    Check the third answer

    C. This way the page explains the failure to a visitor and keeps the protocol status useful to tools.

Socket and virtual host

Listen accepts connections. A virtual host describes eligible behavior at that endpoint. Compare the requested name to the parsed host group.

Directory and URL policy

Directory and Files address the filesystem. Location addresses the URL space. Check merge behavior where these scopes overlap.

Index and listing

An index selects a default file. Listing generates a directory view. A folder can deny both while a named file remains readable.

Parser and request evidence

Syntax, host order and module reports describe a candidate. A targeted request and logs show which behavior the running service produced.

Primary references