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

Chapter 8: Configuring Nginx and Apache

AWS Cloud

8.7 Multiple sites with name-based virtual hosts

Build two sites on one listener, with a distinct name and content tree for each. A deliberate fallback handles requests whose names do not match an eligible site, including typical requests by raw IP.

With Nginx, keep each site's names in its server block and mark the intended default for the shared address and port. With Apache, use a matching Listen endpoint and a virtual host for each site, then check which definition is first in that listener group. Keep the existing default and other sites in the evaluation. A default should have deliberate behavior.

Use the active service's configuration report to verify that each site file is included. Make a reversible, site-scoped change, test and activate it through the correct service workflow, then compare named responses with an unmatched-host control. The private lab below uses request-specific address overrides and synthetic files.

Ravindra Bagale's Tip

If the IP address opens a different site, find the fallback for that address and port. Nginx can mark it with default_server. In Apache, inspect the actual first eligible virtual host rather than relying on its filename.

Lab

In the isolated lab, preserve the listener and URI while varying the requested name. Compare the two existing library names, the new market name, its redirect and the response to an unknown name.

Give two sites distinct names on the same listener

A training institute already publishes a small library website. It wants to add a market page for a student fair. Buying a second public address seems unnecessary because the same web server can deliver both sites. The library and market will have different names, directories and logs. They can share one listening address and port. A request for either name should receive its own content. Requests by an unrecognized name should receive a small documented fallback. When creating the market site, the operator can test all three results while preserving the library definition.

A virtual host is a distinct set of site behavior inside one web server instance. With name-based hosting, the server selects from definitions eligible for a connection address and port using a name supplied by the client. Two clients can connect to the same network socket and send different hostnames. HTTP still has the requested path and other request details afterward. Two sites may both have a route named /ready.txt without sharing a response. The two matching virtual hosts can use different content directories or even different application handlers.

Follow the simple chain for a plain HTTP market request. The client takes market.test from the URL and determines an IP address for it. It connects to that address on the specified port. The server identifies the matching listener. The request still carries the market hostname, so Nginx can choose its market block among those listening there. The selected block then maps the URI to a file or handler. The request for library.test may take exactly the same network path. The hostname changes the site selection after it reaches the listener. That is why issuing a plain request to an IP address alone is an incomplete test of name-based routing.

DNS and web-server selection cooperate but are distinct. DNS answers a client's name lookup. DNS does not normally rewrite the hostname the client sends in its URL-based request. A DNS alias can direct a name to the same destination as another name, but the website still needs to accept or redirect the original name. For example, courses.example.net could resolve through learning.example.net, yet a browser using courses.example.net still requests courses.example.net. If Apache is configured only for learning, the original courses name can reach the fallback. The proper fix might be to declare the alias at the web server, choose a redirect, or correct the request, depending on the intended site design.

In the local lab, curl supplies a connection destination without any public DNS or hosts-file edit. The names end in dot test, a reserved example domain. The client still supplies the name in the URL across the ordinary HTTP exchange. We will record a unique marker for each site and use precisely the same address, port and path. The only input changed between the successful site requests is the authority. Authority identifies the target host and optionally its port for this URL. In a typical HTTP/1.1 request the Host header carries that information. HTTP/2 and HTTP/3 can use an authority pseudo-header with analogous request-routing purpose.

Compare Nginx and Apache on one socket and many site policies

In a basic Nginx HTTP layout, use one server block per independently managed site and list the intended names within it. Both market and library can declare the same listener. A third block can deliberately own the default behavior. The default flag belongs to the address and port in a listen directive. It is independent of what text you use as that server's name. Some examples use an underscore in the fallback block as a conventional non-site name. That text has no special power to select every hostname. The lab uses a reserved fallback name and an explicit default declaration instead.

When a request name is eligible for several Nginx name patterns, exact names are easiest to reason about and take precedence over supported wildcard patterns and matching regular expressions. Wildcards have their own documented rules. An overly broad wildcard can handle a name intended to fall through. Before using one, list the names you expect the site to receive and the names it ought to decline. Duplicate exact names can also produce a conflict in a listener group. A parser may warn that one declaration is ignored while still returning a successful syntax status. Read warnings as well as the exit result, and prove which site answered using a narrow request.

Apache separates its Listen directive from its VirtualHost groups. The applicable address and port select the group, and then its ServerName and ServerAlias entries distinguish sites. In an equal-address name group, the first applicable definition is the fallback if none of the names matches. Its order depends on the configuration actually parsed, not the label a file's author intended. A file named 000-default is convenient when files are read by a suitable sorted wildcard include. A prior explicit declaration can still win. Use Apache's candidate virtual host report to verify the source and order. Test a raw address request separately instead of assuming it belongs to one of the two named sites.

Consider a safe Nginx setup for this exercise: an existing library declaration, an explicit default that responds with a harmless 404 marker, a new independent market file, and a second block for www.market.test whose only purpose is to redirect to the main market name. The library can list books.test as an alias in its own block so both names serve the same content. The market's two names differ on purpose. The primary one serves the files, while the alternate sends a redirect. An alias in this sense lets multiple names select the same site. A redirect is an HTTP response carrying a destination for another request. The two behaviors have different observable results.

Compare the named sites, alias, redirect and fallback
Requested nameSelected policyExpected result
library.testLibrary files200 with the library readiness marker
books.testSame library block as an alias200 with the same marker
market.testMarket files after activation200 with a separate market marker
www.market.testMarket name redirect308 with a Location targeting the main market name
unknown.testExplicit fallback404 with the fallback marker

Why might an operator choose the redirect instead of serving both market names directly? A canonical address is the preferred public name used in links, client configuration and site metadata. A redirect from a supported alternate can help visitors reach that preferred address. Add it using a known target, and verify that it retains the requested path and query when those are intended. The fallback should not reflect arbitrary client-supplied hostnames into redirect links. In the exercise, the www request intentionally uses a fixed known destination, while an unrelated host receives a clear no-site response.

The TLS stage changes the order of evidence. In an encrypted connection a client typically supplies the intended name by Server Name Indication, or SNI, so the server can choose the appropriate certificate before carrying out HTTP request routing. The host field in a request is a separate input afterward. An HTTP redirect sent by an HTTPS site can only occur after the HTTPS connection is established and the client is willing to trust that name's certificate. Verify the certificate and routing for every supported HTTPS name, including an alternate that only redirects. A local plain HTTP test of aliases demonstrates application routing and does not validate any certificate.

Plan the change around the site that already exists

The fair organizers' first decision is to leave the library’s directory and rule in place. Its current listener handles both its known names and perhaps other sites. Preparations for the market include its own content tree, its own selected file under the active configuration include, and a ready marker that cannot be confused with the library. Save the existing named responses before adding the new definition. If you start with only a proposed market page and never record the library's output, it is harder to tell whether a shared setting changed accidentally when the market activates.

A host report, configuration dump or file inspection should answer which names are eligible on the real address and port. Check there is no existing market entry or broader wildcard that is supposed to handle it. Check how the live fallback is chosen and whether the planned new site changes that default. A backup belongs outside every applicable include. If the change is about adding one file rather than modifying an old one, rollback can remove that added file from the include set and preserve a copy elsewhere. Use the project's normal approval and publication mechanism for an existing installation. The lab owns its private include folder, so the staged addition and removal can be rehearsed safely.

Plan at least one before-and-after test for each intended name. Use a marker in the exact same path for the main and alternate library name, distinct bytes for market, an expected redirect status and destination for its alternate, plus a deliberate unknown and raw IP test. The file paths and logs should also be distinct where practical. Separate log streams give better evidence for which site did the work. They do not isolate process resources. Shared virtual hosts can still consume the same CPU, memory, storage, connection pool and failure domain. Independent deployment or security requirements may call for different process or service boundaries beyond what name selection provides.

Add a site without changing the existing one

Use a disposable Bash shell as a regular user with Nginx and curl available. The exercise uses a private Nginx child on 127.0.0.1 port 18889. Choose another unused high port and replace all its occurrences consistently if it is already in use. A collision will be reported in startup or logs, and it is a reason to stop this private attempt. The other user of the port can continue running. No test name here needs a public DNS record, an Elastic IP, or a system hosts-file entry. The two markers are synthetic text files.

First create separate public trees and a scratch root for the configuration and logs. The directory called sites will be selected by an include. The held directory will initially contain the candidate market file outside that include. It also retains the file after rollback. Saving a byte-for-byte copy of the existing library file gives you a way to show that its configuration did not change. The synthetic content files are separate, which lets you observe a server selection error rather than getting identical responses from both roots.

if [ "$(id -u)" -eq 0 ]; then
  printf 'Use a regular practice account.\n' >&2
  exit 1
fi
nginx_bin=$(command -v nginx) || exit 1
vh_lab=$(mktemp -d /tmp/rb-vhosts.XXXXXX) || exit 1
lab_pid=
vhost_cleanup() {
  if [ -n "$lab_pid" ] && kill -0 "$lab_pid" 2>/dev/null; then
    kill -QUIT "$lab_pid"
    wait "$lab_pid" 2>/dev/null || :
  fi
  case "$vh_lab" in
    /tmp/rb-vhosts.??????) rm -r -- "$vh_lab" ;;
  esac
}
trap vhost_cleanup EXIT
mkdir "$vh_lab/library" "$vh_lab/market" "$vh_lab/sites" "$vh_lab/held"
printf 'library-ready\n' > "$vh_lab/library/ready.txt"
printf 'market-ready\n' > "$vh_lab/market/ready.txt"

The configuration uses fixed loopback addresses, with a private PID file and temporary paths. Its log format displays both the host the client supplied and the configured server name associated with the request. That contrast lets you recognize an alias or fallback from a log review. The default file listens on the same endpoint as the library. It returns an explicit status and body rather than silently closing. The file for the market defines a normal content block and a separate redirect block. It is written under held for now, so none of its rules should appear in the initial parse.

cat > "$vh_lab/nginx.conf" <<'NGINX'
worker_processes 1;
pid nginx.pid;
error_log error.log notice;
events { worker_connections 32; }
http {
    client_body_temp_path body;
    proxy_temp_path proxy;
    fastcgi_temp_path fastcgi;
    uwsgi_temp_path uwsgi;
    scgi_temp_path scgi;
    default_type text/plain;
    log_format vhost '$server_name "$http_host" "$uri" $status';
    include sites/*.conf;
}
NGINX
cat > "$vh_lab/sites/00-fallback.conf" <<'NGINX'
server {
    listen 127.0.0.1:18889 default_server;
    server_name fallback.test;
    access_log fallback-access.log vhost;
    return 404 "unknown-site\n";
}
NGINX
cat > "$vh_lab/sites/10-library.conf" <<'NGINX'
server {
    listen 127.0.0.1:18889;
    server_name library.test books.test;
    root library;
    access_log library-access.log vhost;
    location / { try_files $uri =404; }
}
NGINX
cp -p -- "$vh_lab/sites/10-library.conf" "$vh_lab/held/library-before.conf" || exit 1
cat > "$vh_lab/held/20-market.conf" <<'NGINX'
server {
    listen 127.0.0.1:18889;
    server_name market.test;
    root market;
    access_log market-access.log vhost;
    location / { try_files $uri =404; }
}
server {
    listen 127.0.0.1:18889;
    server_name www.market.test;
    access_log market-redirect.log vhost;
    return 308 http://market.test:18889$request_uri;
}
NGINX
cfg() {
  "$nginx_bin" -e stderr -p "$vh_lab/" -c "$vh_lab/nginx.conf" "$@"
}
cfg -t || exit 1
cfg -T > "$vh_lab/parsed-before.txt" || exit 1
grep -E '^# configuration file|server_name' "$vh_lab/parsed-before.txt"

The candidate report should identify the fallback and library site files and the two library names. It should omit the market file even though you can read it separately. The location of a file outside the wildcard explains why it has no effect. Include the parser file-header lines in your observations. A bare search through the temporary tree would find the word market even before the configuration owns any such site. The syntax and dump results describe the exact invocation with the private path.

"$nginx_bin" -e stderr -p "$vh_lab/" -c "$vh_lab/nginx.conf" -g 'daemon off;' &
lab_pid=$!
for attempt in 1 2 3 4 5 6 7 8 9 10; do
  if [ -s "$vh_lab/nginx.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 "$vh_lab/nginx.pid" ] ||
   [ "$(tr -d '[:space:]' < "$vh_lab/nginx.pid")" != "$lab_pid" ]; then
  printf 'The private listener did not start. Check the port and private log.\n' >&2
  if [ -r "$vh_lab/error.log" ]; then tail -n 10 "$vh_lab/error.log" >&2; fi
  exit 1
fi

The PID comparison ensures that the private process you started owns its runtime file before you send requests. Use a simple named GET for the baseline. The probe prints the first status line and any Location header before the body. It deliberately does not follow redirects, so the status belongs to the requested name. The loopback override uses the actual port and URL hostname together. This is a controlled alternative to temporarily editing the hosts file. Even in a real staging environment, the narrow override can help distinguish an origin route from a public name lookup.

probe() {
  local name=$1 path=$2
  printf '\n%s %s\n' "$name" "$path"
  curl --noproxy '*' --max-time 5 -sS --resolve "$name:18889:127.0.0.1" \
    -D "$vh_lab/result.headers" -o "$vh_lab/result.body" \
    "http://$name:18889$path" || return
  head -n 1 "$vh_lab/result.headers"
  grep -i '^Location:' "$vh_lab/result.headers" || :
  head -c 110 "$vh_lab/result.body"
  printf '\n'
}
probe library.test /ready.txt
probe books.test /ready.txt
probe market.test /ready.txt
probe unknown.test /ready.txt
curl --noproxy '*' --max-time 5 -sS -i http://127.0.0.1:18889/ready.txt

Both library names should return 200 and the same body. The market is not configured yet, so its request, the unknown name and the raw address request should reach the fallback. The raw address client supplies the address as its host for this HTTP request. It does not automatically adopt the name in a DNS record or operating-system label. Record the fallback marker and status. These controlled outputs become your old state for rollback. Collect them before putting the market file in the included directory.

test ! -e "$vh_lab/sites/20-market.conf" || exit 1
cp -p -- "$vh_lab/held/20-market.conf" "$vh_lab/sites/20-market.conf" || exit 1
cmp "$vh_lab/sites/10-library.conf" "$vh_lab/held/library-before.conf" || exit 1
cfg -t || exit 1
cfg -T > "$vh_lab/parsed-after.txt" || exit 1
grep -E '^# configuration file|server_name' "$vh_lab/parsed-after.txt"
kill -HUP "$lab_pid" || exit 1

Adding that one file makes its two server blocks enter the same listener group after successful activation. You retain the original archived input and check the library against its independent copy. Review the new dump for the included market entry, the fallback and the existing library file. Read any warning before activating a candidate on an authorized service. The lab example assumes its exact known files and no warning. A HUP sent successfully simply requests activation. Allow a short bounded retry if the first new request still reaches a previous generation, and inspect the private master log if the expected market response never appears.

probe market.test '/ready.txt?from=fair'
probe www.market.test '/ready.txt?from=fair'
probe library.test /ready.txt
probe books.test /ready.txt
probe unknown.test /ready.txt
curl --noproxy '*' --max-time 5 -sS -i http://127.0.0.1:18889/ready.txt
tail -n 6 "$vh_lab/library-access.log"
tail -n 4 "$vh_lab/market-access.log"
tail -n 4 "$vh_lab/market-redirect.log"
tail -n 6 "$vh_lab/fallback-access.log"

The market should supply its own readiness marker at the path, even with a query. The alternate should instead return 308 with a Location identifying market.test on the lab port and preserving the path and query. Request that same destination separately to verify it completes. The fixed host in the redirect definition makes the target independent of which unexpected name a client sends. The other probes retain their baselines. In particular, the unrecognized host does not start redirecting just because a valid alternate name exists. Check the library log for the books alias and the fallback log for the raw address and new unknown probe.

The rollback is to remove the market entry from the include set while keeping the known training copy available. Move the active copy to a path the parser does not read, test the reduced candidate and signal the same private parent. The old library file should still match its known copy. Probe the market and its alternate after activation. They should again produce fallback, while both library names work. A known absence is the expected restore for a newly added site. Then remove the disposable environment with the handler attached to your shell.

mv "$vh_lab/sites/20-market.conf" "$vh_lab/held/market-removed.conf" || exit 1
cmp "$vh_lab/sites/10-library.conf" "$vh_lab/held/library-before.conf" || exit 1
cfg -t || exit 1
kill -HUP "$lab_pid" || exit 1
probe market.test /ready.txt
probe www.market.test /ready.txt
probe library.test /ready.txt
probe books.test /ready.txt
vhost_cleanup
trap - EXIT
test ! -e "$vh_lab" && printf 'Virtual host lab removed.\n'

Repeat the rollback probes before cleanup if the earlier generation was still answering immediately after the activation request. Save your output locally before the final lines remove the generated files. Your report should connect each result to its hostname, configured server and address. If you changed the port during setup, include the actual number you used. The point is to show the effect of a small included-file change and compare all the names it can influence.

Verify the whole redirect journey and the shared service boundary

It is easy to count supported names and forget a redirect has two request outcomes. Work through the market's alternate with its intended query value. A visitor opens http://www.market.test:18889/ready.txt?from=fair. The connection goes to loopback in the lab. The site for the alternate receives the original name and returns a 308. A 308 Permanent Redirect is a response that can be cached by a client and preserves the request method when followed. For this exercise the method is GET. The redirect's Location contains the fixed canonical hostname and same path and query. The client's next connection can still go to the same socket even though its host value is now market.test. Then the ordinary market block sends the expected body. Each part of that trace explains a specific property the team wanted.

During the active stage, use two address overrides to verify the whole journey with curl. The test is controlled because both expected names map to the same isolated loopback listener and the earlier first-hop inspection confirms the exact target. Starting with separate requests remains useful if a redirect fails. It shows precisely which part of the initial response was wrong. The complete run gives a second view that resembles a visitor following the alternate link. The write-out values are printed after the final body so you can save both states in the report.

curl --noproxy '*' --connect-timeout 2 --max-time 5 --max-redirs 1 -fsS -L \
  --resolve www.market.test:18889:127.0.0.1 \
  --resolve market.test:18889:127.0.0.1 \
  -w '\nredirects=%{num_redirects} status=%{http_code} final=%{url_effective}\n' \
  'http://www.market.test:18889/ready.txt?from=fair'

Expect the market marker, a count of one redirect, final status 200 and the canonical URL with its query value. If you supply only one override for the initial name, the second hop can use ordinary name resolution instead. The dot test names in this fixture require the second override because we did not put them in public DNS. Avoid using a redirect-following probe as your only check after a real service change. A redirect from the library or fallback could eventually end at the same working market page and still violate the proposed routing policy. The separate host and status checks remain meaningful.

The library has a different alias goal. Books visitors should simply see the library page under the requested name. An ordinary request for books should make zero redirects. A successful body matching the library is appropriate there because that is the outcome the definition deliberately shares. A normal client still uses the books authority in its URL. If the two domains need shared login state or separate web permissions, design those properties explicitly. Browsers generally distinguish origins using scheme, hostname and port, and cookie scope has its own rules. Using one server process or one Apache alias does not merge the two browser origins. Likewise, two names accessing the same underlying application do not guarantee separate application data.

Use this exercise to write two meanings of separation. An HTTP selection boundary can send site-specific files, logging and redirects according to request authority. An operating boundary determines which processes and credentials are shared, how resources are limited and what else stops when a host is unavailable. A team sharing a physical instance may be comfortable with one operational domain but still need independent behavior for each public site. Two unrelated organizations may need stronger isolation for recovery and access. The virtual-host plan gives evidence for correctly selected routing, while the larger deployment plan establishes the security and operational boundaries.

Keep track of the address family and front-door protocol when you turn these local examples into a rollout. A public rollout with IPv4 and IPv6 can give one name two routes. Both routes should reach the intended HTTPS and HTTP policy if you advertise them. A name that resolves successfully on the workstation does not mean the same edge is reached on every family. Also check unusual variants that users really type, such as an expected alternate or a supported port. Leave intentionally unsupported names to the documented fallback. An acceptance report is clearest when it records exactly which routes and names were verified. That gives a new team member a reproducible check rather than an unqualified statement that the domain works.

For the isolated classroom comparison, use the reserved examples and a local resolution override. This keeps the evidence independent of public DNS ownership and makes each request's chosen destination visible in the command.

If your config change is only adding the market definition, report what its rollback actually reverses. Deactivating its file changes which site can respond for the market names on that listener. It does not automatically remove any public DNS record, externally managed certificate, documented link, browser-cached redirect or saved release directory. Decide which of those separate dependencies is part of the authorized change. The clean lab leaves them out to keep one cause visible. In a production plan, record them with their own verification so a timely rollback of the virtual host does not leave users seeing an unexplained public route.

Treat duplicate-name warnings as meaningful even when syntax passes

The exercise so far has one site definition for each supported name. Real sites acquire revisions, backups and aliases over time. A configuration can accept the file syntax and still report a duplicate name on the same listener. In that case, the default or first available worker may remain healthy while one proposed block will never receive the requests it is expected to handle. This is a semantic warning about which rule is used, not necessarily a parser error that causes a nonzero status. Read the whole diagnostic for a candidate, including warnings emitted to standard error.

To see a controlled example, run the preparation, configuration, startup and before-check in a fresh lab. Write the duplicate declaration below while it is running. The older library file already contains books.test. The added declaration uses the same exact name and address with a distinctive response. Run the configuration test and inspect the warning and its exit status. This is an intentionally unapproved candidate in the temporary fixture. Never signal the lab parent with it in the include list. Move the test file outside the active pattern before any activation. This exercise changes a candidate file only and shows what a test can tell you before workers see an edit.

cat > "$vh_lab/sites/90-duplicate.conf" <<'NGINX'
server {
    listen 127.0.0.1:18889;
    server_name books.test;
    return 200 "duplicate-candidate\n";
}
NGINX
test_status=0
cfg -t > "$vh_lab/duplicate-check.txt" 2>&1 || test_status=$?
printf 'config test exit status %s\n' "$test_status"
cat "$vh_lab/duplicate-check.txt"
mv "$vh_lab/sites/90-duplicate.conf" "$vh_lab/held/duplicate-rejected.conf" || exit 1
cfg -t || exit 1
probe books.test /ready.txt

The verified local Nginx build produced a conflicting server name warning and a successful syntax status. The existing library alias still returned the correct body. That response is unsurprising because you never asked the running process to adopt the duplicate candidate. A second diagnostic after the move should omit the conflict. The report distinguishes three states: the already running rule, the duplicate on disk as seen by a syntax test, and the repaired candidate. Your real operator workflow should also distinguish these states instead of assuming a test attempted activation.

Suppose two people independently add different files inside an include directory. One adds a redirect from an alternate name, and the other enables that name as an alias for another site. The later conflict may be difficult to recognize just by looking at each file alone. Search the parser output for all declarations of the name in the relevant listener group. Compare them with your site's ownership policy. Keep the correct declaration and preserve the rejected candidate outside the include during review. The fix should clarify ownership, rather than merely moving the duplicate ahead in file order so a different block unexpectedly wins.

Diagnose name resolution, TLS and request routing with different evidence

A workshop visitor says they directed a new name to the server but still see the library. First ask whether they used the new name in the URL or browsed directly to a number. A raw IP request can normally fall into the default while a real named request works. Second check the actual address and port they reached. The hostname might resolve to a different machine, a load balancer or a stale local setting. Third inspect the named site report and origin log under the intended endpoint. Do not start by deleting a packaged default site. The lab's control keeps a predictable default, which makes wrong destinations and missing names observable.

Here is a partial diagnosis. The public resolver returns the correct origin address for both names. A forced name-and-destination origin probe for the new market gives the explicit fallback marker. This result isolates at least one problem to the HTTP endpoint you tested. The host may be missing from the selected site file, not enabled, or associated with the wrong listener. Use the Nginx configuration dump or Apache's site report with the actual startup settings. If the name appears in the candidate but the old process was never reloaded, the correct files on disk and fallback on the live service can both be true. Check the activation evidence and logs before concluding that DNS is still wrong.

Compare a second scenario. The direct named origin probe returns the market marker, but ordinary browser requests reach another site. The authoritative records, caching resolvers, HTTPS front door, forwarded host and a proxy's cache can each account for a different route. Determine which one answered. Read the public edge's request log if available. If using a reverse proxy, review whether it intentionally changes the host presented to the backend. A proxy can choose a backend itself and supply an expected upstream Host value. When a backend selects virtual sites by the original authority, passing an unintended value can steer it to a default. That is a separate setting from the DNS records that guided the first connection.

Inspect certificate errors in their own stage. If a user tries HTTPS, a certificate chosen for the library does not become valid for the market because the server would eventually recognize the market Host header. The TLS connection must complete first. Configure certificates and eligible names for the actual encrypted listener. Then test without bypassing verification, including any alternate hostname that only sends an HTML-level or HTTP redirect after the connection. Check the correct public-facing termination point, which may be a load balancer rather than the origin. A plain HTTP reproduction on loopback demonstrates name selection after connection, not public TLS setup.

Be deliberate with aliases. Following the alternate market URL includes two HTTP requests when its redirect succeeds. The first request tests the alternate site policy and its Location response. The second tests the canonical site's actual body. Write both in the acceptance sheet. If the first returns 308 but the destination returns bad content, the redirect does not pass the user journey. If the second works but the first silently serves an unrelated site, a valid destination alone does not prove the alternate behaves. For protected sites, verify both layers using the approved user access route.

Log evidence helps identify names without exposing unrelated data. The local format prints the requested authority and the matched configured name, plus the URI and status. It excludes the query string. A production URI or request line can contain sensitive information, so select diagnostic fields appropriate to your use case. A shared access log can still separate site names if the fields are chosen well. Separate logs can still mix information if both definitions point at the same file. Trace the file and format from the selected context rather than assuming the filename on disk identifies its contents correctly.

Read an equivalent Apache plan and verify its own defaults

The lab uses Nginx to perform a live add and restore. Apache can express a similar intended routing plan with a Listen directive for the shared endpoint and separate VirtualHost sections. The common address and port are listed on each relevant section. Inside a library section you can declare its main name and an explicit alternate with ServerAlias. The market's main name would have a different DocumentRoot and narrowly scoped matching Directory rules. A separate alternate redirect can be handled by an appropriate Apache directive rather than by simply listing that alternate as an alias. Test the behavior you intended, not just whether the name appears somewhere in the parsed output.

Focus on how to read which definition would be the fallback. Suppose the expected candidate has three groups for one address. Apache reports a dedicated fallback first, then library, then market. You can keep library second and market last while adding an exact ServerAlias to the library where needed. If a test reports market as default instead, inspect the actual include ordering and exact endpoint group. A filename called 00-fallback does not apply before an earlier explicitly read virtual-host section. The correct Apache config check includes the chosen candidate path, and the correct live probe uses the port and intended name. See the Apache configuration reading lesson for an independently tested first-host fallback and ServerAlias example.

For a design exercise, write the proposed matching table with one row for library, books, market, the www market alternate, an unknown name and the raw address. Include expected response marker, status and, for the redirect, the exact scheme, authority and path. Write down how either engine would implement a fallback. Then identify what you must inspect in the actual package to prove that policy is active. Complete the exercise by recording a second control for at least one asset path. A default site can serve its own homepage when the intended request fails, so broad positive status checks are insufficient without site-specific evidence.

Interview questions, short quiz and revision cards

Why can two names reach two websites without two IP addresses?

The connection can arrive at the same listener. The client still sends the intended name in the request, allowing the web server to choose a matching virtual host. TLS can also use the wanted name during setup. The ultimate body comes from that site's mapping or handler.

Why doesn't a DNS alias automatically serve the canonical website?

The alias helps resolve the caller's original name to a destination. A client normally still uses that original name in its request and for HTTPS expectations. Configure the alias or redirect at the web service too, and verify any required certificate names.

Why could an unknown name display a library page with a successful status?

The library might be the default for that address and port. For Apache it can be the first eligible virtual host; for Nginx inspect the default listen option or fallback order. Use explicit hostname and address in the next probe so you know which rule to expect.

What does a 308 from an alternate name prove?

It proves that the initial request got a permanent redirect response. Inspect its Location, then verify that following the intended target gives the correct body. If the first request used HTTPS, both its TLS setup and that of any HTTPS destination need to validate.

Do separate server blocks isolate all outages and credentials?

No. They can isolate name selection, content path and logging policy. The sites can share the same server process, operating-system permissions, host resources and failure domain. Use a separate security or operational boundary when those shared risks are outside your requirements.

Quick quiz

  1. Both names resolve to one IP. The same path gives different expected body markers if only the hostname changes. What did the server select?

    1. Two virtual hosts inside one eligible listener group
    2. Two different application routes because their URI paths changed
    3. Two different DNS servers because the markers differ
    Check the first answer

    A. The fixed destination and URI control for the other variables, and the matched names distinguish which configured site serves the body.

  2. An alternate hostname on HTTPS should redirect to the main hostname. What is needed on the initial request?

    1. Only a successful certificate check on the final host
    2. A valid TLS connection for the alternate name before its HTTP redirect can be trusted
    3. A different IP address for every redirect
    Check the second answer

    B. TLS happens before HTTP routing. A browser cannot rely on a redirect it never received because the first connection failed verification.

  3. Nginx returns a successful syntax status with a duplicate-name warning. What is the next useful action?

    1. Activate it because the exit status is zero
    2. Delete the unrelated fallback
    3. Review the applicable declarations and intended owner before activation
    Check the third answer

    C. The warning concerns actual matching, not punctuation. Verify which site should receive that name and keep exactly the intended declaration.

Three independent inputs

Keep address, port and URI fixed while testing each hostname. The body should identify the selected virtual site.

Alias or redirect

An alias can serve the same site directly. A redirect sends a destination for a second request that also needs testing.

Explicit fallback

Verify the default on the correct address and port. An unmatched name should get the policy you intended.

Unrelated site control

Compare the existing site's body and configuration before activation, after adding the new site, and after recovery.

Primary references