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

Chapter 9: Domain Names, DNS and Subdomains

AWS Cloud

9.8 Configure the web server for the domain

DNS brings the visitor to your IP. The web server must now recognise the name. That's why you write the domain in server_name or ServerName.

# Site excerpt for a reviewed listener on an authorized server
# Adjust the listener only for the intended address families.
server {
    listen 80;
    server_name dairy.example.test www.dairy.example.test;
    root /srv/dairy/site;
    index index.html;
    location / {
        try_files $uri $uri/ =404;
    }
}
# Site excerpt. The service needs an existing appropriate Listen directive.
<VirtualHost *:80>
    ServerName dairy.example.test
    ServerAlias www.dairy.example.test
    DocumentRoot "/srv/dairy/site"
    <Directory "/srv/dairy/site">
        AllowOverride None
        Require all granted
    </Directory>
</VirtualHost>

For an authorized configuration change, test the exact candidate with the correct Nginx or Apache invocation, apply it through its managed service and verify the intended named response. Use the private exercise below to practice the whole name-selection check without editing a system site.

Review the existing address, hostname and fallback configuration. Add only the intended named site or its required redirect. Keep each other configured site in its approved scope.

Ravindra Bagale's Tip

Decide how both the bare name and www should behave. If they share content, configure both accepted names. If www should redirect, give it a matching rule and verify the initial status and destination.

Lab

Chala, run the private loopback exercise below. Check the named main page, alternate-name redirect, destination asset and unrelated site separately. No public DNS or system service changes are needed.

Got it? DNS is the address, and server_name is the name on the door – only when both match does the visitor reach the right home. Now let's move on to verifying DNS.

Give the correct website its own name and response

Friends, the dairy's DNS plan now points customers to a prepared address. On that system, two websites can share a listener. One holds the dairy schedule and another holds a separate training portal. A visitor asking for the dairy name should never get the portal just because both use the same IP address. The server needs a rule that recognizes the requested hostname and sends the request to the intended site. That rule, together with the listener and content handler, is what this lesson sets up and tests.

Think of the earlier chapter about request routing. DNS helps produce a network destination for a hostname. A listener is the address and port where a web server accepts the connection. The HTTP request identifies the intended host and path. The server uses those inputs to select a configuration and response. In ordinary HTTPS, TLS negotiates before that HTTP request. The host is relevant to the certificate as well as the later routing. A named site can fail even while a lookup and a connection to the same address work correctly.

Use reserved names for all practice. We will create a private Nginx instance with the fictional dairy's bare name, a www name with a deliberate redirect, and a separate portal. All share one loopback port. An unknown name will produce a clear fallback response. You will check several body markers, the redirect's destination and a missing path, so you can identify which handler answered. We will also read how the equivalent Apache site decisions are expressed. The exercise needs no public DNS change or global service controls.

First write a simple requirement. The bare dairy name should serve its named homepage and a notice asset. A request to the www form should redirect the same requested path to the chosen canonical host. The portal should keep responding with its own marker. An arbitrary unfamiliar host should not expose the dairy page. A canonical hostname is the spelling the site chooses as its preferred public name. Giving both names identical content can also be a valid design if intended. Here the redirect lets us show the difference between DNS association and an actual HTTP response.

Find the listener and the default behavior

A web server listens on a local address and port. The connection arrives at a socket before site rules are chosen. A configured site name becomes relevant within the appropriate listener selection. If the service only listens on IPv4 but the domain advertises an applicable IPv6 address, some clients will not be exercising that listener. If a frontend is a reverse proxy, load balancer or CDN, identify which component receives the original connection, its TLS responsibility and which host information arrives at the backend. Be clear about which layer the exercise is verifying.

Nginx uses the listen directive inside a server block. Several compatible blocks can share the same bind, and server_name declares which names belong to a block. The default choice is associated with the relevant address and port. If the requested name fails to match an applicable name, the server can select its configured default for that listener. A literal underscore used by some examples does not create a universal wildcard. A private test with an explicit default and two distinct named sites makes the behavior easy to see.

On Apache, an appropriate Listen rule is needed for the intended address and port. A <VirtualHost> block then describes which requests can use its site rules. Apache first narrows to the best connection address and port, then checks names among the eligible virtual hosts. ServerName identifies the site and ServerAlias can add accepted names. If no name matches in the eligible set, the first matching address-and-port virtual host is normally used. Naming a virtual host is therefore different from creating the listening socket and from choosing an intentionally safe default.

On an existing host use the actual installed service, its configuration selection and the configured enabled-site mechanism. Some Nginx installations read matching files under conf.d. Ubuntu package configurations commonly read enabled-site links. Apache's Ubuntu package provides an enabling helper for its packaged layout. The exact locations depend on the effective configuration. Avoid creating a second independently managed process on a production socket. A site file under a familiar name may be ignored if the running service reads another entry file or include path.

Map the selected names to files or applications

Once a site is chosen, its route or document root supplies the content. In Nginx, the common root mapping adds the URI to a base path. An index rule can select a default file for an appropriate directory visit. Apache normally adds the requested path under its DocumentRoot for simple static files, and a matching directory context provides relevant access policy. In each case check the exact physical content and permissions for the selected site. Adding a host to a block with the wrong root can consistently return the wrong page.

Suppose the dairy's homepage exists in an approved release folder while a generic welcome page remains in the package's original web root. A matching named site should read the release folder. If a direct IP probe still sees the welcome page, that may be the intentional default. Inspect which name and configuration each request used. The earlier labs used body markers to prove which handler ran. For a resource with a matching site and wrong file, check the effective root or location and the attempted path in the log. A path issue does not call for a domain transfer.

File paths are operating-system data. Make sure the worker can traverse the necessary directory levels and read the intended files under the actual policy. A 403 could come from a server rule, OS access or additional security controls, and a missing file can become 404. Avoid making broad mode changes as a shortcut. When the installed setup uses SELinux or another mandatory policy, relevant denial evidence guides a scoped correction. When proposing a shared document root, verify that it exposes only the desired files and that the service does not use an unrelated site's directory.

Many applications sit behind a proxy location. The same name selection still happens on the frontend. Then the path can be forwarded to an app listener or other configured handler. Record which component should supply the body for each path. A frontend can serve a local schedule file correctly and fail one proxied pickup route if the app does not recognize its path. The test plan should reflect those dependencies, such as one known HTML body, one asset and one safe application response. An interview answer that asks only whether “the server is up” misses them.

Choose equivalent names or a deliberate redirect

If the dairy wants both names to serve identical content, one web site rule can accept both. For Nginx this can be a server_name list. In Apache it can be one ServerName and one ServerAlias within the selected virtual host. Each public name still needs an appropriate DNS arrangement and TLS coverage if the user visits HTTPS. The additional name is one deliberately supported spelling. In the exercise we instead want the browser to see the bare name after a request to www, so we use a dedicated named redirect rule.

A redirect is an HTTP response with an applicable status and target. For the practice setup, a temporary 302 sends the visitor from the exact www owner to the bare dairy host. The destination uses an explicit trusted name and the original path and query for this route contract. It does not derive the target host from an arbitrary incoming Host value. A temporary redirect is easy to evaluate before settling permanent behavior, and it is also a deliberate project choice. For real forms or non-GET requests, select status and allowed behavior according to the application, since redirection can affect the method and body used on the next request.

When checking a redirect, capture the first status and Location value before automatically following it. If both the fallback and canonical site have valid-looking pages, a final 200 can conceal a detour. A missing or repeated redirect can also create a loop if both names point clients back to each other. The practice explicitly follows the planned response in a separate controlled request. Track which host and path should be present at each step. This verifies the redirect logic and its destination's serving behavior separately.

A CNAME that refers www to the bare domain helps locate the endpoint; the browser continues to use its original URL until a web-level action changes it. Setting a name in a server block does not publish a DNS answer either. That is why we supply a per-request loopback mapping during practice. In a deployed setup, check both the ordinary name lookup and the actual server's response. If port and name are correct but one asset is missing, you now have reasons to examine location and document root rather than restarting the DNS investigation.

Run a private named-site and redirect exercise

Use a disposable Linux learning machine with Python 3.7 or newer, curl and Nginx supporting the separate bootstrap error log option. Use an ordinary account. The block creates a generated configuration, two tiny static files and logs in a single new directory. It uses an available loopback port picked for this run and a private process. Read the expected results before running it. The bare dairy name should return the designated content. The www alias should return a 302 whose destination preserves the intended asset path and sample query. The unrelated portal and unknown-host fallback should retain their own outcomes.

A small interval exists between Python's selection of an available port and the web server binding it. If another local process takes that port first, leave its owner alone and read the scoped startup diagnostic. The lab cleans up its own files and you can rerun with a fresh choice. All configured IPv4 listeners bind only to loopback. Where an Nginx binary is unavailable, use the sequence and expected answers as a paper exercise. This block never needs to select a production unit or change the system's name lookups.

python3 - <<'PY'
import os
from pathlib import Path
import signal
import socket
import subprocess
import tempfile
import time

if os.geteuid() == 0:
    raise SystemExit("Use a regular local account for this exercise.")
subprocess.run(["nginx", "-e", "stderr", "-h"], check=True, capture_output=True)

dairy = "dairy.example.test"
www = "www." + dairy
portal = "portal.example.test"
unknown = "unknown.example.test"

def probe(host, port, target):
    args = [
        "curl", "-q", "--noproxy", host, "-sS", "--include", "--max-time", "3",
        "--resolve", f"{host}:{port}:127.0.0.1", f"http://{host}:{port}{target}",
    ]
    result = subprocess.run(args, check=True, text=True, capture_output=True, timeout=5)
    header, body = result.stdout.split("\n\n", 1)
    status_line, *fields = header.splitlines()
    headers = {key.lower(): value.strip() for key, value in
               (line.split(":", 1) for line in fields)}
    return int(status_line.split()[1]), headers, body

with tempfile.TemporaryDirectory(prefix="dns-vhost-lesson-", dir=Path.home()) as scratch:
    lab = Path(scratch)
    root = lab / "site"
    (root / "assets").mkdir(parents=True)
    (root / "index.html").write_text("Dairy collection home", encoding="utf-8")
    (root / "assets" / "notice.txt").write_text("Collection notice", encoding="utf-8")
    with socket.socket() as reservation:
        reservation.bind(("127.0.0.1", 0))
        port = reservation.getsockname()[1]

    config = lab / "nginx.conf"
    config.write_text(f"""
worker_processes 1;
pid "{lab}/nginx.pid";
error_log "{lab}/error.log" notice;
events {{ worker_connections 32; }}
http {{
    log_format routing '$host $server_name $request_uri $status';
    access_log "{lab}/access.log" routing;
    client_body_temp_path "{lab}/body";
    proxy_temp_path "{lab}/proxy";
    fastcgi_temp_path "{lab}/fastcgi";
    uwsgi_temp_path "{lab}/uwsgi";
    scgi_temp_path "{lab}/scgi";
    default_type text/plain;
    server {{
        listen 127.0.0.1:{port} default_server;
        server_name fallback.example.test;
        return 404 "Unknown site";
    }}
    server {{
        listen 127.0.0.1:{port};
        server_name {dairy};
        root "{root}";
        index index.html;
    }}
    server {{
        listen 127.0.0.1:{port};
        server_name {www};
        return 302 "http://{dairy}:{port}$request_uri";
    }}
    server {{
        listen 127.0.0.1:{port};
        server_name {portal};
        return 200 "Portal stays available";
    }}
}}
""", encoding="utf-8")
    nginx = ["nginx", "-p", f"{lab}/", "-c", str(config), "-e", str(lab / "bootstrap.log")]
    subprocess.run(nginx + ["-t"], check=True, timeout=5)
    process = subprocess.Popen(nginx + ["-g", "daemon off;"], start_new_session=True)
    try:
        for attempt in range(25):
            if process.poll() is not None:
                raise RuntimeError((lab / "error.log").read_text())
            try:
                if probe(dairy, port, "/")[0] == 200:
                    break
            except subprocess.CalledProcessError:
                pass
            time.sleep(0.1)
        else:
            raise RuntimeError("The private site did not start as expected.")

        path = "/assets/notice.txt?shift=am"
        status, headers, _ = probe(www, port, path)
        expected_location = f"http://{dairy}:{port}{path}"
        print("First www response:", status, headers.get("location"), flush=True)
        assert status == 302 and headers.get("location") == expected_location

        cases = [
            (dairy, "/", 200, "Dairy collection home"),
            (dairy, path, 200, "Collection notice"),
            (dairy, "/missing.txt", 404, None),
            (portal, "/", 200, "Portal stays available"),
            (unknown, "/", 404, "Unknown site"),
        ]
        for host, target, expected_status, expected_body in cases:
            status, _, body = probe(host, port, target)
            print(host, target, status, body if expected_body else "(error response)")
            assert status == expected_status
            if expected_body is not None:
                assert body == expected_body
        print("\nHost, selected site, path and status:")
        print("\n".join((lab / "access.log").read_text().splitlines()[-6:]))
    finally:
        if process.poll() is None:
            process.send_signal(signal.SIGQUIT)
            try:
                process.wait(timeout=5)
            except subprocess.TimeoutExpired:
                os.killpg(process.pid, signal.SIGKILL)
                process.wait(timeout=5)

assert not lab.exists()
print("Private server and temporary files cleaned up.")
PY

The loopback connection is forced inside each curl invocation while the URL retains the selected hostname. The probe includes response headers and reads the first response without following its redirect. Status and Location are observed together. The notice request is then tested on its actual destination. This gives two linked proofs: the redirect points to the intended name and the resulting destination returns the intended body. When making a real safe test, preserve any required query behavior and confirm that the target does not bounce back to the original name.

Notice the two requests that show 404. The first uses the proper dairy host but an absent path, so the relevant handler is the dairy site. The second uses an unknown name and reaches the explicit fallback with its own marker. The browser status might look similar, but the routing decisions are different. Read the access rows with HTTP host, chosen server name, requested URI and response status. The recorded selected site helps explain why the fallback and missing-file cases should be described separately. Also verify the portal's recognizable success marker. The dairy's name setup has no reason to change that separate response.

The temporary config contains no certificate, HTTPS listener or public addressing. Its result establishes HTTP mapping and the first redirect for this private process. In an approved ordinary HTTPS test, the initial www connection must get a matching valid certificate before the redirect is observable. Plan the proper HTTPS destination and certificate identities for both sides. Keeping the lab plain HTTP gives a small isolated way to reason about named routes without claiming a TLS result. The companion HTTPS lesson builds that part of the chain.

When the script exits, it sends the private process a scoped shutdown signal, waits for it, and deletes its own temporary directory. It does not restart another installed Nginx or use the service manager. Important example log lines have already been printed. Copy the relevant evidence into a worksheet before forgetting which behavior was planned. If you run on a shared machine, identify the owned scratch location and process if interrupted externally. Cleanup should not assume every process with a similar executable name belongs to the lab.

Translate the same decisions into Apache settings

On an installed Apache server, first find the intended Listen arrangement and the process that owns the address and port. A valid <VirtualHost> block does not create a listening socket by itself. If you are reviewing an already managed service and the listener exists, do not add a duplicate Listen blindly. Ask what the current unit starts and which sites are enabled. For a standalone isolated fixture the configuration must explicitly supply its own listener and required modules. Chapter 6 used that approach for a temporary Apache exercise.

# Example site excerpt for an authorized service with a matching listener
<VirtualHost *:80>
    ServerName dairy.example.test
    ServerAlias www.dairy.example.test
    DocumentRoot "/srv/dairy/site"

    <Directory "/srv/dairy/site">
        AllowOverride None
        Require all granted
    </Directory>
</VirtualHost>

This alternative Apache sketch is for the design where both approved names serve the same content, not the separate redirect contract tested above. The address and port describe eligible connections, and the name directives distinguish the request from other virtual hosts. The document root and filesystem section describe access to the intended files. A standalone deployment still needs the right process, listener, modules and any packaged environment. Keep the content folder and permitted access matched to the intended public files. An exact prefix or socket for a private site may differ from the wildcard shown here.

For a redirect-only Apache virtual host, the intended name can select a distinct block using a documented redirect configuration supported by the active module. Choose the response code and explicit destination according to the application. Then test the initial response and destination as separate requests, just as you did with Nginx. In a multi-site change, a read-only virtual-host dump through the correct package wrapper helps identify which host list the current config declares. It cannot replace the observed named result. The Debian or Ubuntu enabling workflow differs from RPM-based installations, so use the verified controls for the actual distro.

Apply a scoped real configuration only after review

On the authorized machine, start with a verified backup or versioned comparison of the actual site file and related include or enablement state. Confirm the intended document root and which hostnames already exist. Check the active listener and read the related site configurations; do not create an accidental second default or duplicate name rule. Review how they will interact. Application-facing config belongs to the intended service, and public DNS belongs to its authorized zone provider. Prepare both as part of the plan, while validating each independently.

Use the correct server configuration test and control mechanism for the instance you own. A standard Nginx setup can test with its selected nginx -t invocation. Apache commonly uses the package's appropriate apachectl configtest or apache2ctl configtest. A passing parser does not guarantee a particular hostname uses the intended handler. Apply using its approved service method if the configuration requires it, then test exact known names, paths and planned responses. The management lesson's private candidate exercise shows the difference between a test that succeeded and a reload whose runtime result was observed.

Give a clear handoff if the change fails. If the default answers to the intended name, inspect the actual connection binding and loaded site rules. If the correct site answers but one file fails, compare the location or directory and selected path with the log. If TLS fails, find the component that accepted the TLS handshake. If a neighboring site changed unexpectedly, compare configuration scope before applying further edits. The recovery plan should preserve the earlier working config and record how to restore it through the same authorized process if appropriate.

On some real hosts, a default site also deliberately denies unrecognized names or supplies a neutral page. That is a valid choice. Do not cause arbitrary external names to depend on your new website by treating every accepted socket connection as a known hostname. Check the currently intended fallback behavior and existing sites. The private lab uses a harmless explicit 404 to distinguish that behavior. Choose the corresponding test for the actual service requirements. The proof you want is that the intended host begins returning the correct result while other planned behaviors keep their scope.

Test each public name and the features it needs

Build the acceptance table before changing the shared configuration. Write one row for each intended request. Include the scheme and port, host, path, expected response status and a recognizable body or Location. A home route can exercise the site's document index. A notice asset can prove requests to a dependent path work. A second already running site gives an unchanged comparison. For the canonical redirect, first check a request to the alternate name. Then try the reported destination explicitly. These results are small enough to record in a few minutes and specific enough for a second engineer to reproduce.

When verifying the intended public HTTPS setup, include the exact certificate identity for the starting hostname. The client cannot read the redirect until the initial connection meets ordinary expectations. Consider a client that uses the www name and the endpoint presents a certificate that only matches the bare name. Even impeccable redirect logic inside the www server block cannot solve the certificate stage. Check the component that terminates TLS and its matched certificate. Report both which name is configured for HTTPS and which name the site uses after the redirect.

For a real service with a load balancer or proxy, the backend may see a connection from that frontend and host values the frontend constructs or forwards. Record which rules use the original name and what address or port the target really listens on. An origin test can help identify a working handler, while a normal external request proves the service path that includes the intermediary. If those results differ, find which component generated the status or body. A media file stale at the CDN and a missing file on the origin demand different checks. Asking which endpoint generated the response will save repeated origin restarts.

Check required address families separately if the public design publishes both. IPv4 and IPv6 may reach different bindings or frontends. A correct server_name on an IPv4 listener cannot fix an unready IPv6 path elsewhere. A supporting NS or A check does not test the network route. Make a controlled request to the right host under each planned family, and keep the real destination and response evidence. If an IPv6-only client is outside the approved test scope, report the missing verification accurately and include it in the deployment conditions.

Finally confirm logging and cleanup. If the service has separate site access logs, capture only the specific permitted rows needed for the change. The sample log records the requested host, selected server and URI. HTTP queries can contain details a production log should handle according to its policy. Keep the lab's sample query harmless. Mark the exact private process and scratch files removed after the test. For live work, the tested candidate and before-state version should already be known to the authorized operator so an appropriate recovery is possible.

Use one symptom to narrow the next check

The name resolves and the wrong site appears. Record the exact URL and which address actually responded. Use a known named probe and compare the body and any applicable host-selection log. Keep the destination fixed and compare the intended name with a plausible fallback name. If the named request reached the default, inspect the relevant listener and loaded server configuration. If the site name appears in a file that was not included, the text itself has not proved active configuration. Verify enablement, authorized apply and runtime response together.

The correct homepage works but its file path fails. The host criteria appear to have selected the intended site for at least one route. Determine which exact path the browser requested for the missing file. An absolute asset URL could use a different hostname. A relative one could resolve differently if the page moved under another path. Compare the applicable route, physical file and access rules in the service's current configuration. Check whether the backend or static handler knows that URL. A correct DNS record can be unrelated to the asset failure. Record the matching log rather than assuming every 404 comes from the same cause.

Only the alternate name fails. Compare its DNS owner and record with the bare name, then test the intended connection and certificate under the alternate URL. On a shared frontend, the alternate may resolve to the right address and still lack a matching site or TLS name. If the alternate should redirect, verify the first response code and precise location with its actual query behavior where relevant. If the alternate is meant to be an independent site, grouping it as an alias of another site could be incorrect even if both responses return 200.

A second website changes during the edit. A listener, global include or shared root could have affected more than the intended site. Review the exact config diff and whether the change shifted a directive to a wider scope. Evaluate the neighboring site's known route using its exact name. The confirmed response from the second site is useful evidence for the release's boundaries. If it differs unexpectedly, restore the approved previous configuration where appropriate and correct the scope before another apply. Avoid restarting unrelated services to see whether the result changes back.

Use the four cases to practice an evidence handoff. Put the earliest verified successful stage beside each symptom. A valid A result may prove the name association while the connection remains untested. A TCP connection establishes contact without proving a TLS certificate is suitable. TLS can succeed before the server's route returns the wrong file. A successful file response can still be the wrong body. The result that matters is the one described by the customer and your expected named route. Keep the intermediate observations in chronological order so the next engineer understands which part was verified.

One final scenario concerns a supposedly tested redirect. A colleague shows a final screenshot of the dairy home and claims the extra name is ready. Ask for the first status and Location and the actual URL at the end. If the browser had a cached redirect, the new server rule might not have been exercised. A fresh controlled request recording the initial response is better evidence for the current path. Then compare the target separately and verify the original host's HTTPS identity where applicable. This is the exact design practiced in the loopback lab.

Design a second route without changing public DNS

Draw a second virtual host for a fictional event name. Decide whether it should point to the same file tree or its own content. Explain which scheme, network destination and listener it uses and which name rule distinguishes it. Specify a marker for the event response and one route that should remain with the dairy. Then add a row for an unfamiliar host. The result passes if your partner can identify the addressed listener and expected HTTP handler for each request from the notes, whether they select Nginx or Apache to describe it.

For a code variation on a copy of the lab, add a new named Nginx server under the same loopback listener and return a one-line marker. Extend the cases to assert it without changing the original valid rows. Review the effective configuration before running it. Use a distinct reserved name and a scoped per-invocation mapping. A failure in the previous portal or default rows can reveal that your change affected more of the listener than planned. The script's temporary scope prevents a test name from affecting any production virtual host. For Apache, write a corresponding site excerpt and explicitly identify the configured listener and module assumptions.

A second design task is to decide how the alternate name handles a path that exists only on the bare site. If the project wants the landing page for every alternate request, the expected target path differs from our preserve-path exercise. If the project wants the same path and query, write the exact expected Location for one example. Decide how an intentionally unsupported path should behave and test the first response and final status. Explicitly state what happens to a non-GET request if your scope includes one. This avoids promising a redirect preserves behavior the application never tested.

Check your proposed changes with the version and packaging actually installed. A standalone excerpt can omit process ownership, log paths, module includes and service start options. An existing package site file can depend on them. In a separate private fixture you can supply those details yourself. For an authorized live change, use the existing managed process and current site activation rules. In either case, explain the intended root and fallback before applying. Success is the named behavior and preserved comparison, supported by known configuration and logs.

Try comparing a log that records the client-supplied name with a log that also records the chosen server. At the beginning of each request the client proposes the hostname. The program then matches an applicable virtual host or falls back. The expected log for the unknown name can therefore contain two different name fields. The first says what was requested and the second says which configuration served it. That distinction is useful in a shared environment because a single IP address or an access log with only a generic status can conceal both selections. A diagnostic log format is part of the evidence design, and production policies determine what fields can be retained.

For another exercise, have your partner propose changing only an alias in the named website while leaving the content directory untouched. Write which requests would change site selection and which would still see their previous responses. If the old alias label is still actively used by customers, identify its deliberate replacement or redirect rather than assuming it can disappear immediately. DNS for the earlier hostname might still point to this listener and lead to fallback after the config change. This can happen even when no DNS record was edited. The web configuration's accepted name list is an independent part of the contract and deserves its own before-and-after test.

Finally, a useful published configuration comment says what the rule is intended to establish. One might say this site serves the dairy's exact name, while another block handles its explicit alias. A comment that says “works for all names” leaves too many questions, especially if the behavior depends on listener order or TLS. In your practical handoff, state the normal host and alternate policy, the relevant process, and the expected comparison requests. A new operator should be able to read the comments alongside the actual response evidence. They can then update just the scope that was approved without needing to guess whether a generic fallback page is part of the site.

End by connecting these checks to the student's original reason for the lesson. The business puts a public name on a receipt. Its customer needs that name's correct page and working links. Every layer you checked exists to make that visible result repeatable.

Explain the selected host and path

What must happen after DNS provides the address of a shared web server?

The client must connect to an appropriate address and port. For ordinary HTTPS it negotiates and verifies TLS, then sends the identified HTTP request. The server uses the relevant listener, hostname and path to select the intended configuration and response. I would test the actual named URL and a useful marker. An IP-only status can be from a fallback and leaves site selection unproven.

How does Nginx choose a site when two names use one address and port?

It considers the relevant listener and matches the name against eligible server configurations, using the listener's default when appropriate. I would read the applied configuration and verify a named request. Checking the actual body or chosen site in a correlated log can distinguish that from a fallback that also returned an HTTP status.

What is the job of Apache Listen compared with VirtualHost?

Listen opens the local port and address. A virtual host describes the rules for eligible connections and accepted names. I would first determine which socket the running service owns, then inspect the proper virtual host and record its required module and document root behavior. A valid virtual-host stanza alone does not create the listener.

How do you support the alternate www name without showing two competing pages?

Choose the site's canonical behavior. If the names should share content, configure the appropriate accepted names in the site and verify their DNS and certificates. If www should redirect, configure its own matching handler with an explicit approved destination. Test the first response and actual target. The CNAME can help the client locate the endpoint but does not produce the redirect.

Why might a preview test pass even though the public site is not ready?

The preview can force a destination and exercise the named host and path without depending on normal DNS or public network policy. It may also use a different scheme. I would keep the preview result and separately verify real DNS, external reachability and approved TLS for the normal request. The preflight supports those later checks without claiming them early.

What should be compared when an unrelated site shares the same server?

Record a baseline host, path and marker for that site's existing behavior. Use the same comparison after the scoped apply. Review any shared listener, default setting, include and directory rules when the result changes. This makes it possible to confirm the change selected the new domain correctly while preserving the existing site.

Find the distinguishing probe

  1. Two names reach the same listener. The dairy shows its marker and the portal shows its own marker. What made the difference?

    Answer and reasoning

    The request hostname selected an eligible server block with different handling. Both paths can use the same TCP destination. The distinct response bodies and selected site log fields verify the behavior.

  2. A missing dairy file and an unknown domain both return 404. How do you tell the causes apart?

    Answer and reasoning

    Compare the exact requested name and path and the selected site in the appropriate logs. The first reached the named dairy route, while the other reached the explicit fallback. A single status can describe different handling decisions.

  3. A public HTTPS visitor requests a name you intend to redirect. At what point will they require the proper certificate?

    Answer and reasoning

    During the initial TLS negotiation for the requested name, before the ordinary HTTP redirect can be received. The destination then needs its own appropriate TLS and route behavior.

  4. A candidate Apache file defines a virtual host for a new port. What must you inspect before assuming that port is reachable?

    Answer and reasoning

    Confirm the correct Listen arrangement and running service socket, then check authorized network access. The virtual-host stanza selects eligible traffic and does not itself open the port.

  5. The named homepage returns 200. Which extra observation proves a planned redirect points to the intended notice file?

    Answer and reasoning

    Inspect the first status and Location from the alternate name with the notice path. Then verify the named destination returns the expected notice body. The homepage alone does not check that path or transition.

Cards for a shared web listener

One address can serve many names

Match an authorized request to its socket, hostname and route. A known body shows which handler responded.

Give the fallback an intended result

Check how unknown names behave on the relevant listener. Verify other named sites through that same path before and after a change.

Read the first redirect

Compare the initial status and Location with the intended target. Test the destination separately and preserve ordinary TLS checks.

Use the active configuration

Inspect actual includes, service selection and listener. Validate and apply only through the intended scope.

Know which layer you tested

A private forced-address request proves named behavior along that path. Plan the separate public DNS, ingress and HTTPS checks.

Official references