Chapter 7: Static Website Hosting (3 OSes × 2 Web Servers)
7.12 Hosting multiple sites on one server (virtual hosts)
Think of one building with many shops: the building has one address (IP), but each shop has its own name board (domain). Technically, the browser sends the domain in the HTTP Host header, and the web server picks the matching server_name / ServerName block. Mauli Dairy's order site and blog on one server work exactly this way.
एक बिल्डिंग, अनेक दुकानं असं समजा: बिल्डिंगचा पत्ता एक (IP), पण प्रत्येक दुकानाचा नावाचा बोर्ड वेगळा (डोमेन). टेक्निकली, ब्राउझर HTTP Host हेडरमध्ये डोमेन पाठवतो, आणि वेब सर्व्हर जुळणारा server_name / ServerName ब्लॉक निवडतो. Mauli Dairy ची ऑर्डर साइट आणि ब्लॉग एकाच सर्व्हरवर – याच पद्धतीने.
एक बिल्डिंग, कई दुकानें ऐसा समझो: बिल्डिंग का पता एक (IP), लेकिन हर दुकान का नाम बोर्ड अलग (डोमेन). टेक्निकली, ब्राउज़र HTTP Host हेडर में डोमेन भेजता है, और वेब सर्वर मैच होने वाला server_name / ServerName ब्लॉक चुनता है. Mauli Dairy की ऑर्डर साइट और ब्लॉग एक ही सर्वर पर – इसी तरीके से.
One server can host many websites; the web server chooses the site by the Host header (domain name) sent by the browser.
orders.mauli.example.test ─┐ ┌─► /var/www/mauli-orders-shared-lab
├─► 192.0.2.25:80 ────┤
recipes.mauli.example.test ─┘ (one IP, one port) └─► /var/www/mauli-recipes-shared-lab
# Nginx: one server block per site
server { listen 80; server_name orders.mauli.example.test; root /var/www/mauli-orders-shared-lab; }
server { listen 80; server_name recipes.mauli.example.test; root /var/www/mauli-recipes-shared-lab; }
# Apache: one VirtualHost per site
<VirtualHost *:80>
ServerName orders.mauli.example.test
DocumentRoot /var/www/mauli-orders-shared-lab
</VirtualHost>
<VirtualHost *:80>
ServerName recipes.mauli.example.test
DocumentRoot /var/www/mauli-recipes-shared-lab
</VirtualHost>
For a real deployment, publish DNS records for the approved stable destination and verify each name individually. An Elastic IP is one option for a direct EC2 IPv4 endpoint. For this local lab use curl’s temporary hostname mapping to the approved listener, so no purchased domain or system hosts-file edits are required.
Ravindra Bagale's Tip
For a public portfolio, use your approved DNS name and HTTPS. Verify the endpoint address, the certificate name and the specific vhost response. For this lesson the loopback lab is enough to prove both virtual hosts. An Elastic IP can stabilize a directly associated public IPv4 address and does not manage DNS or certificate updates.
Ravindra Bagale's Tip – मराठी
Public portfolio साठी मंजूर DNS नाव आणि HTTPS वापरा. Endpoint address, certificate मधले नाव आणि vhost response तपासा. या धड्यासाठी loopback lab मध्ये दोन्ही virtual hosts तपासता येतात. Elastic IP मुळे जोडलेला public IPv4 स्थिर ठेवता येतो. DNS आणि certificate updates वेगळे करावे लागतात.
Ravindra Bagale's Tip – हिंदी
Public portfolio के लिए मंजूर DNS नाम और HTTPS इस्तेमाल करो। Endpoint address, certificate में नाम और vhost का response जाँचो। इस अभ्यास में loopback lab से दोनों virtual hosts जाँच सकते हो। Elastic IP जुड़े हुए public IPv4 को स्थिर रखने में मदद करता है। DNS और certificate के updates अलग से करने पड़ते हैं।
Lab
Chala, khalcha lab kara. Tyach approved listener var orders ani recipes chi vegvegli hostname vaprun request kara. Donhi about pages madhlya olakhichya lines tapaasa. Ek unmatched name vaprun default response pan compare kara.
Give two websites their own names on one web server
Mauli Dairy publishes a simple order information site and a separate blog of recipes. The dairy manager signs off on order hours while a different editor approves the blog. The two sites use the same machine and ordinary HTTP listening port in the classroom, but they must use different file trees and logs. A revised recipe should not alter the displayed order hours. A link to the orders site should stay within the orders site unless the author deliberately links elsewhere.
A virtual host is a set of website settings within a server process. Each set can recognize particular names and select its own document root, logs, error behaviour and access rules. This is what lets one listening service serve the two dairy sites. The two sites can have the same path, for example /about.html, with two independent responses. We will track the request from its name and address to the selected site, then test deliberately correct and unmatched names.
This page uses HTTP on loopback for the main lab. The loopback address is available to programs on the same machine and does not require public DNS. The names are reserved for testing, and the content is synthetic. An approval workflow for a real shared server must preserve each site's behaviour, including the intended fallback and which deployment role can change which public files. The lesson's separate logs and acceptance tests show how to check those responsibilities.
Follow two names to one address and two document roots
Start from these URLs: http://orders.mauli.example.test/about.html and http://recipes.mauli.example.test/about.html. The scheme says to speak ordinary HTTP, whose default port is 80. The name helps the client find an address and tells the HTTP service which site the client intended. The path identifies the desired resource within that site. The address in this example can be the same for both. The filename can also be the same. The name-to-site decision makes the selected local path different.
| Client's URL host | Training destination | Selected site root | Response to /about.html |
|---|---|---|---|
orders.mauli.example.test | One approved IPv4 address at port 80 | /var/www/mauli-orders-shared-lab | Order collection contact information. |
recipes.mauli.example.test | The same IPv4 listener | /var/www/mauli-recipes-shared-lab | A note about the recipe editor. |
| An unknown test name | The same IPv4 listener | Determined by the intended fallback | The lab's deliberately identified fallback body. |
The client normally asks the domain name system, abbreviated DNS, which network destination to contact. For a local exercise a per-command override can name a loopback address while keeping the chosen name inside the URL. After connecting, an HTTP/1.1 request normally carries that name in the Host header. Later HTTP versions ordinarily use an equivalent authority field. The server uses this name when deciding which eligible website should handle the request. A client can therefore make several different site requests through one open service, even though they all name the same network destination.
With Nginx the listen address and port first select a group of server definitions. The requested name selects a matching server_name among applicable blocks. In Apache the best address and port group determines which set of virtual host definitions is considered and the name can match ServerName or ServerAlias. Looking only at names from a config dump can obscure this first grouping. A name declared in a group for a different actual destination may never be considered for the test connection.
The destination still matters when the names agree. Imagine someone cloned the training instance and left both virtual host definitions in place. A request can use the orders hostname and get old hours if it connects to that earlier clone. Compare the address or temporary override with the real instance record, then look for a current body marker and the corresponding access entry. The selection trace ends with the expected release, rather than stopping as soon as the hostname sounds correct.
Decide what an unmatched hostname should see
When the requested name is not recognized, the selected listener has fallback behaviour. Nginx can designate a default_server for an address and port, and falls back to the first applicable block for the listener if none is explicit. Apache uses the first matching-address vhost for an unmatched name within that eligible group. A fallback often shows a packaged welcome page on a fresh machine. On an established host it may belong to an existing site or a dedicated neutral response. Determine the current behaviour before adding new definitions.
Pointing a DNS name to the machine does not make it valid for these site definitions. The server can still answer a request with the fallback. If a raw-IP URL returns the orders page, that can also be a sign the orders block became the default for that group. It would be poor evidence that the recipes name works. Check both intended names and one specified unmatched name. The three responses should be independent enough that a reader can identify which block handled each request by its marker or log.
For your isolated lab create a separate fallback with an obvious marker such as “Training listener fallback”. It holds synthetic material and no private metadata about the other sites. On the assigned system, keep the existing approved fallback unless the owner explicitly plans a change. For an Apache machine where you add the first virtual host to a socket, the old main server response can be replaced by that group's first virtual host behavior. Preserve a baseline probe before adding a new group, and include fallback expectations in the acceptance note rather than trying to infer them from file order later.
Nginx's server_name _ appears in some fallback examples. The underscore is a literal placeholder name. The default_server property of the affected listen address and port actually sets the fallback. Similarly, naming an Apache file 000-default.conf is a packaging convention that can make it load first in a sorted include, not a special priority attached to all files with that name. Check the effective config and actual socket group to know what applies.
Plan who can change each site's document root and rules
Prepare a public release manifest for the two Mauli sites. Give each its own index.html, about.html, and a stylesheet with an identifying marker. For the orders homepage use “Mauli order collection desk”, and for the recipes homepage use “Mauli recipe notebook”. Link to the contrast as a purposeful change, for example an absolute URL for the other site only when that navigation was requested. Paths beginning with / within a page normally refer to that page's own host root. They do not refer to the operating system directory names where you placed the public files.
On a managed server the two release roots should be controlled by their approved publishers. Give the worker service only the necessary access to the published files and directories. Two virtual hosts in the same process are routing choices, and the worker may read files from both because it needs to serve them. This is a different isolation property from independent operating system users, separate processes, containers or independent hosts. A directory name and a distinct access log do not create a security boundary between untrusted administrators.
If both sites are maintained by the same trusted team, a shared server can make administration smaller and reuse a listener. That also means the sites share capacity and the service lifecycle. A configuration change that prevents the process from starting, a filled filesystem or a resource-intensive site can affect the other one. The class workflow uses separate release roots and configuration files plus a preflight and acceptance check. For distinct trust boundaries or independently managed availability goals, consider a deployment model with stronger separation and validate it against those requirements.
Keep each site's logs identifiable. A named access log can establish which site served a particular path. The error log can show a denied local path or a configuration issue for its block. If a controller or management tool uses a bulk include, changing or reloading one candidate can still parse all enabled sites. Preserve valid config for the complete service and run acceptance probes for the requested change as well as an existing site's known paths. An owner who can independently deploy a public file still needs coordination for shared service configuration.
Compare the same design in Nginx and Apache syntax
Use one block per site. On an approved Nginx lab the blocks can share a listen address and port and use explicit names and distinct roots. Put them under an included HTTP context for the guest. Confirm that each root contains the approved files and that the expected MIME mappings are active. The staged example deliberately omits a change to the current fallback. In the local exercise below we control its fallback ourselves.
server {
listen 80;
server_name orders.mauli.example.test;
root /var/www/mauli-orders-shared-lab;
index index.html;
location / {
try_files $uri $uri/ =404;
}
access_log /var/log/nginx/mauli-orders-shared-lab.access.log;
}
server {
listen 80;
server_name recipes.mauli.example.test;
root /var/www/mauli-recipes-shared-lab;
index index.html;
location / {
try_files $uri $uri/ =404;
}
access_log /var/log/nginx/mauli-recipes-shared-lab.access.log;
}
Each name stands on its own line with an explicit root in the same block. Copying the second block and forgetting to change its root can still produce responses for both recognized names. Distinct markers are an inexpensive way to catch the error. A duplicate name on the same applicable listener can cause Nginx to ignore a later declaration and report a warning. Read any warnings from nginx -t and examine the expanded inputs with nginx -T. The parser's success status does not confirm that each requested website selects its own content.
<VirtualHost *:80>
ServerName orders.mauli.example.test
DocumentRoot "/var/www/mauli-orders-shared-lab"
<Directory "/var/www/mauli-orders-shared-lab">
Options None
AllowOverride None
AllowOverrideList None
Require all granted
DirectoryIndex index.html
</Directory>
</VirtualHost>
<VirtualHost *:80>
ServerName recipes.mauli.example.test
DocumentRoot "/var/www/mauli-recipes-shared-lab"
<Directory "/var/www/mauli-recipes-shared-lab">
Options None
AllowOverride None
AllowOverrideList None
Require all granted
DirectoryIndex index.html
</Directory>
</VirtualHost>
The Apache definitions belong under the approved distribution-specific include. The main server configuration controls whether Apache actually listens there. Check the parsed map with the control command appropriate to that system, for example apache2ctl -S on Ubuntu or httpd -S on the expected RPM installation. Use separate logs when you carry this exercise into multiple active vhosts, and put them under the host's approved log directory and formats. Each directory grant is scoped to the public release, so the server does not need to grant access to unrelated parents or staging areas.
Choose the syntax for the service assigned in the exercise. There is no reason to start two independent web servers to bind the same socket on the managed machine just to compare their configuration expressions. Stage the files and configurations according to the relevant distribution lesson. The local fixture can select either service on an unprivileged port and gives equivalent response checks for each. It provides a comparison without moving any current site between daemons.
Lab one. Verify two names on the same approved listener
Use the assigned server with either Apache or Nginx, the two synthetic public release trees and an approved IPv4 listening socket that accepts local requests on port 80. If using Apache on a fresh instance, check the fallback decision explained above. Identify the existing intended fallback before adding the new sites. Prepare an about page for each release with a marker that differs between the two. Keep the releases' files in separate directories and confirm their permissions or SELinux contexts following the guest's rules.
(
set -eu
addr=127.0.0.1
for name in orders.mauli.example.test recipes.mauli.example.test; do
printf '\n%s\n' "$name"
curl --noproxy '*' --resolve "$name:80:$addr" \
--silent --show-error --max-time 5 --include \
"http://$name/about.html"
done
curl --noproxy '*' --resolve "unknown.mauli.example.test:80:$addr" \
--silent --show-error --max-time 5 --include \
http://unknown.mauli.example.test/
)
Both about pages should have status 200 and match the correct site. The third request should match the previously recorded fallback policy, which need not be status 200. Read the full response around the blank line that ends its headers. The text below that line is the body that confirms which public site answered. If your listen address is not a wildcard and does not include loopback, use the appropriate address for the designated local client. Repeat the procedure for a remote client only through an approved delivery path.
Check the result of changing one site's file as an exercise. The recipes editor changes the synthetic about page to say that reviews happen on Friday. Keep the exact previous bytes separately before changing the file, and use only the approved public release. The next direct request to the recipes about page should carry the new marker. Repeat the orders about and fallback checks and compare them to their recorded outputs. If the orders site also changes, inspect whether the blocks share a root unintentionally or whether the request used the wrong name. Restore the original recipe marker when that is the requested cleanup.
In your evidence note include the daemon and parsed site map, the source or override used for destination selection, each host value and each requested URL. Match the HTTP result to the expected log for that site. A single working homepage with a screenshot is weak evidence when the task is to route several independent names. The point of the exercise is the contrast between responses using the same network destination. Show that contrast clearly enough for a reviewer to repeat it.
Lab two. Run the same request matrix with a temporary server
This exercise needs Python 3 and an approved Nginx or Apache 2.4 executable. For Nginx, use the default engine and set VHOST_BIN only when its executable is outside your shell's search path. For Apache, set VHOST_ENGINE=apache. You can point to a compatible module directory with VHOST_MODULE_DIR on an installation with a different layout. These optional shell variables change only this exercise's command choices. Run as your ordinary user. The fixture chooses a high loopback port and creates a fresh working directory and PID file.
python3 - <<'PY'
from http.client import HTTPConnection
from pathlib import Path
from tempfile import TemporaryDirectory
import os
import shutil
import socket
import subprocess
import time
engine = os.environ.get("VHOST_ENGINE", "nginx")
if engine not in ("nginx", "apache") or os.getuid() == 0:
raise SystemExit("Choose nginx or apache and run as an ordinary user.")
fallback_bin = (shutil.which("nginx") if engine == "nginx"
else shutil.which("httpd") or shutil.which("apache2"))
binary = os.environ.get("VHOST_BIN") or fallback_bin
if not binary:
raise SystemExit(f"Use an approved local executable for {engine}.")
sites = (
("fallback", "fallback.example.test", "Training listener fallback"),
("orders", "orders.mauli.example.test", "Orders about the collection desk"),
("recipes", "recipes.mauli.example.test", "Recipes about the editor"),
)
with TemporaryDirectory(prefix="mauli-vhosts-") as folder:
base = Path(folder)
for key, name, marker in sites:
(base / key).mkdir()
(base / key / "about.html").write_text(marker + "\n")
with socket.socket() as chooser:
chooser.bind(("127.0.0.1", 0))
port = chooser.getsockname()[1]
conf = base / "server.conf"
if engine == "nginx":
paths = ("client_body", "proxy", "fastcgi", "uwsgi", "scgi")
temp_paths = "\n".join(f'{p}_temp_path "{base / p}";' for p in paths)
blocks = []
for key, name, marker in sites:
default = " default_server" if key == "fallback" else ""
blocks.append(f"""
server {{
listen 127.0.0.1:{port}{default};
server_name {name};
root "{base / key}";
access_log "{base / (key + '.access')}";
}}
""")
conf.write_text(f"""
pid "{base / 'pid'}";
error_log "{base / 'errors'}";
events {{ worker_connections 20; }}
http {{
{temp_paths}
types {{ text/html html; }}
{"".join(blocks)}
}}
""")
argv = [binary, "-e", "stderr", "-p", str(base) + "/", "-c", str(conf)]
run_flags = ["-g", "daemon off;"]
else:
candidates = ("/usr/libexec/apache2", "/usr/lib/apache2/modules",
"/usr/lib64/httpd/modules")
mods = os.environ.get("VHOST_MODULE_DIR") or next(
(d for d in candidates if Path(d, "mod_mpm_event.so").is_file()), "")
if not mods:
raise SystemExit("Set a directory of modules matching your Apache binary.")
builtin = subprocess.run([binary, "-l"], capture_output=True, text=True,
check=True).stdout
modules = []
for name in ("mpm_event", "unixd", "authz_core", "mime", "log_config"):
if f"mod_{name}.c" not in builtin:
modules.append(f'LoadModule {name}_module "{Path(mods) / ("mod_" + name + ".so")}"')
(base / "types").write_text("text/html html\n")
blocks = []
for key, name, marker in sites:
blocks.append(f"""
<VirtualHost 127.0.0.1:{port}>
ServerName {name}
DocumentRoot "{base / key}"
<Directory "{base / key}">
Options None
AllowOverride None
Require all granted
</Directory>
CustomLog "{base / (key + '.access')}" "%r %>s"
</VirtualHost>
""")
conf.write_text("\n".join(modules) + f"""
ServerRoot "{base}"
DefaultRuntimeDir "{base}"
PidFile "{base / 'pid'}"
ServerName fallback.example.test
Listen 127.0.0.1:{port}
ErrorLog "{base / 'errors'}"
TypesConfig "{base / 'types'}"
<Directory "/">
Require all denied
</Directory>
{"".join(blocks)}
""")
argv = [binary, "-f", str(conf)]
run_flags = ["-DFOREGROUND"]
subprocess.run([*argv, "-t"], check=True)
daemon = subprocess.Popen([*argv, *run_flags])
try:
for attempt in range(60):
if daemon.poll() is not None:
raise RuntimeError("Fixture stopped before accepting requests.")
with socket.socket() as check:
if check.connect_ex(("127.0.0.1", port)) == 0:
break
time.sleep(0.05)
else:
raise RuntimeError("Loopback listener did not become ready.")
def get(host, marker):
conn = HTTPConnection("127.0.0.1", port, timeout=3)
try:
conn.request("GET", "/about.html", headers={"Host": host})
response = conn.getresponse()
assert response.status == 200, (host, response.status)
assert response.getheader("content-type").startswith("text/html")
assert marker in response.read().decode()
print(f"{engine} {host}: {marker}")
finally:
conn.close()
get(sites[1][1], sites[1][2])
get(sites[2][1], sites[2][2])
get("unmatched.mauli.example.test", sites[0][2])
(base / "recipes/about.html").write_text("Recipes due Friday\n")
get(sites[2][1], "Recipes due Friday")
get(sites[1][1], sites[1][2])
for key, name, marker in sites:
assert "GET /about.html HTTP/1.1" in (base / (key + ".access")).read_text()
finally:
daemon.terminate()
try:
daemon.wait(timeout=7)
except subprocess.TimeoutExpired:
daemon.kill()
daemon.wait()
PY
With either compatible server, expect three initially distinct markers. After the synthetic file update, the recipe editor's Friday marker appears only under the recipe hostname, and the order marker remains the same. This is an ordinary local filesystem update to that fixture, so no configuration reload is needed for the change in body. The script also checks that each destination block logged an about-page request. Apache chooses the first eligible fallback in the fixture and Nginx has an explicitly configured default listener.
If you run both variants, compare the results from the equivalent requests. The paths and markers should match their case across the two servers. Package-specific service names and configuration locations are outside this temporary process. A missing module or incompatible binary can prevent a fixture from starting; verify the matching build rather than modifying system package rules. Another process can take the chosen port in the short gap between selection and activation. Restart the fixture to pick another private port. The script stops its child process and removes the scratch tree after completion or assertion failure.
For the lab, give each tester the literal expected hostname and URL path, not only the server address. With a multiple-site service each acceptance line should also say which virtual host is expected to handle that URL. This distinguishes a named-route requirement from a general test of whether port 80 has a working service.
Choose an explicit host name and alias plan
Choose which names are part of each site. For a real release, orders and www.orders could be two intended names on one origin. In Apache a ServerAlias can make a second name choose the corresponding site. In Nginx a single server_name directive can list exact names for the same configuration. A separate redirect to one preferred canonical name is a further decision. Plan what the client should receive for each supported alias and test both the initial status and final URL if you add a redirect.
Exact names are simple to review. Wildcards are convenient when a class has intentionally delegated a predictable range of names. They also cover more names than students sometimes realize. For Nginx, exact names take precedence over wildcard forms and regular expressions according to documented matching rules. Apache checks eligible names and aliases in its processing order. A duplicate declaration can have surprising results and arrive without a fatal syntax error. Put ownership for each public name in the release inventory and avoid overlaps when defining the simple dairy sites.
DNS must make each intended client connect to the right endpoint. An A record supplies an IPv4 address, and an AAAA record supplies an IPv6 address. A DNS alias can point through another supported name. These records express routing information for the client. The HTTP server still has to recognize the names it receives and bind the relevant addresses. If one name has both IPv4 and IPv6 records, verify both paths where clients use them. A stale AAAA pointing elsewhere can produce a different reader experience from a correct IPv4 curl test.
On EC2 an Elastic IP is one way to hold a public IPv4 address under the relevant AWS allocation and association. It is not required to learn virtual hosts, and it does not maintain DNS records or certificates automatically. A load balancer or another approved front door can give a deployment a different stable target. Decide who controls the address or name before updating DNS. Use an isolated local override to verify the origin first, then check the real client path separately. Leave test-only names outside public DNS.
Explain the additional name decision in HTTPS
Ordinary HTTP can send its host information shortly after a connection opens. For HTTPS the TLS handshake comes first. The client typically provides the requested DNS name during the handshake using Server Name Indication, often shortened to SNI. This can let the endpoint select the matching certificate and TLS policy. The client then checks whether it can trust the certificate and whether it identifies the server for the requested name. After this handshake, the protected HTTP request carries its own authority and path information.
That sequence matters when testing two TLS sites on the same address. Setting an HTTP Host header while the URL contains an address can change the HTTP name without providing the intended DNS name in the TLS handshake or the correct name for certificate verification. Use the expected HTTPS URL and a scoped address override when testing the approved TLS listener. Test the certificate and response for every supported name. An HTTP virtual host that passes the fixture has not yet demonstrated an HTTPS deployment.
For a hostname change, divide the plan into name resolution, certificate identity and HTTP site selection. A newly pointed DNS name can lead to a valid machine and still fail certificate checks. A successful handshake does not ensure the server used the correct public file after HTTP arrived. The next lesson covers the certificate step more fully. For this one, deliver a precise record of which plain HTTP host and path pair returned each sample file.
Use hostnames for routing and separate them from access policy
In the local test, the client software set the HTTP host information itself. Anyone who can reach a listener and send an ordinary HTTP request can choose a name value, independent of how they learned the network address. Therefore the site name is generally a routing input. It does not prove a user is a member of the dairy or that a visitor came through a specific DNS record. If order records or staff tools need restricted access, keep them outside the public static root and use the site's approved authorization and network controls as appropriate.
For the same reason you should plan what an unmatched request does. A shared generic fallback can show a neutral message without listing the real public sites. On a training service a clear fallback marker simplifies the test. On a real server meet the site's approved fallback policy, which may be a static neutral page or an error response. This is a policy design choice with a concrete test: use a dedicated approved unmatched name and compare it to the deliberately chosen status and body.
Host names and URL paths can be confused when content references another site. A link at /about.html on the recipes host remains on that host. A link that explicitly starts with the orders URL sends a new request for the other host. An HTTP redirect can do the same by telling the client a different target. Browse the site's linked URLs in the acceptance check. The names might both work on the server yet send users across the wrong roles if the public pages were copied from one site to the other without reviewing their navigation.
Make the ownership scope clear before a shared reload
Imagine the orders owner requests a changed pickup time. Record the orders release root, the site definition and the old body marker. There is no reason to replace the recipes file during that change. If the update changes only the bytes of a public HTML page in the current orders directory, apply it through the approved file deployment. Verify it with that host. If the update changes the orders root to a separate release, record the original and candidate root, check the whole managed service's config and select the approved activation action. Shared service state makes the latter action broader than a file update.
Make a scoped private backup of any configuration file you plan to change. Record whether its available definition and enabled entry are separate. A backup copied into a wildcard include can become a second active declaration, especially when it has the expected suffix. Keep such copies outside the active configuration tree. Preserve both vhosts and the global settings that affect them through the owner-approved server backup or change record. This gives you evidence to restore the exact definition and prior root if the new route shows the wrong site.
Validate the edit by reading the full eligible site group for the affected address. Check root, explicit host names, and any old aliases or catch-alls. A different file may contain a duplicate name. A test that dumps the parsed map helps find the relevant source and shows more than looking at only the new snippet. After applying the shared config, verify the orders and recipes names with separate markers, an asset per site, and the retained fallback. Where the owner already has a health check for another authorized site, run that check through its intended endpoint as agreed.
Record what happened before and after in the same simple matrix. A shared host can be busy, so make the probes precise and limited. Logging every file extensively is unnecessary for this check. Choose one or two endpoints that identify the site and exercise the particular change, then compare their bodies and statuses. If the orders change must be reverted, restore its own configuration and release pointer, validate the whole service configuration and verify both expected sites again. Recovery here is observable independently per host.
Choose a next observation based on actual request evidence
| Symptom | Test | Potential cause to distinguish |
|---|---|---|
| Both names return the orders marker. | Compare two explicit host probes, the effective vhost group and each root. | One host may miss the configured name and get the default, or both configs may point to the same folder. |
| The recipe homepage works but its about page returns 404. | Request the exact path for the same name and compare its own file manifest and log. | The named site is present but its release might lack that path. |
| Local orders works and the public name shows another server. | Compare public DNS answers with the approved origin or front door, and repeat the same scheme and path. | The public request may follow another address, proxy, route or cached response. |
| HTTP serves the correct site but HTTPS fails validation. | Check the HTTPS URL, listener and presented certificate for that name. | A prior TLS decision may prevent any accepted HTTP request. |
| The fallback changes after adding the recipe vhost. | Compare address grouping and the explicit or effective default before and after activation. | A new site may have changed the selected address set or fallback order. |
The first row offers a good reasoning exercise. A body from the orders root alone does not identify which vhost handled it. If the recipes access log received the request, the recipe block may be using the orders root. If the orders or default log saw it instead, examine name eligibility first. Compare the effective configuration around the reported site names and the request you sent, including any port relocation by a proxy. That evidence determines whether to change the content path or the site selection rule.
When another component sits in front of the service, its configuration also participates. A public reverse proxy can accept the original connection, choose an upstream based on the hostname, and send a new HTTP request to that upstream. It can preserve the original host information or supply a different configured host for the next hop. Verify the approved forwarding policy and which component is expected to terminate TLS. A successful direct loopback test covers the application's origin rules only. A successful request through the front door covers the full tested route at that moment.
Use specific deltas when diagnosing web content. If only the CSS differs, compare the two sites' relative stylesheet references and their named asset requests. If the whole response comes from another site, investigate the host and address choices. If nothing connects, inspect service and network reliability before opening a file editor. Reproduce the smallest failing request followed by one known-good control. For example, the two about routes on one listener make it easy to spot an incorrect common root.
Keep a previously shared address working during a name change
Suppose the manager originally gave readers a recipe subdomain and later asks to rename it to a shorter one. Determine whether the old name should still serve the recipe content, redirect readers, or retire. DNS configuration is necessary to take the old hostname to a listening server during a transition. The virtual host or redirect configuration must recognize the old and new names according to that plan. If the old URL uses HTTPS, it generally needs a valid certificate identity to complete the handshake before the redirect can be seen.
Write down a test case for the original URL including its about path. A redirect test should record the initial response and target before checking the final page, otherwise a client could report only a successful endpoint and hide an incorrect intermediate URL. Make a separate request to the new name and verify its distinct marker. Test the orders control with the same approved destination. A renamed recipe site should have no reason to change the orders name or its release. The expected fallback provides a third control when comparing the parsed result.
Allow for caches in an actual migration. A DNS answer includes a time-to-live, which influences how long it may be retained by resolvers. HTTP redirect responses can also be cached under applicable rules. A local address override bypasses the configured address resolution for that client and therefore verifies only the forced destination. Take a separate normal public reading from the approved client path once the name change is live. Before retiring the earlier address, confirm which traffic still depends on it and which site or administrator owns it.
Restore the prior fallback and keep independent releases usable
To end a disposable managed lab, record which of the two site definitions and roots it created. Remove them individually under the approved distribution's site management procedure, and keep the old fallback. On a link-based layout disable those exact enabled entries and retain their definitions until verification. For a direct include move the owned site candidates outside the active input directory according to the guest's process. Check that the remaining config parses and contains the intended other sites. Reload the approved service and exercise the baseline requests before removing the experimental files.
Remove only the synthetic roots that have no remaining reference. If a real DNS zone was used in a separate approved exercise, its records have their own rollback, including the time other clients can retain old answers. Endpoint cleanup and DNS update are different actions. Preserve resources still used by an unrelated site. The private loopback fixture does not require these changes. Its two temporary sites and fallback are contained in one scratch filesystem tree and one child process.
Make a final handoff with the names, route, release versions and fallback evidence that were tested. Note what was simulated, including any test DNS override. Keep the request and body marker for each name so another learner can use the same comparison. When a task is to change one of two sites, the record should show both the requested site's outcome and the observed existing behaviour for the protected site. That is how independent named routing becomes a property you can verify.
Interview questions with explained answers
How can two sites share an IP address and port?
A client connects to a server address and port, then supplies the desired name in the HTTP request. The web server uses the applicable address group and name to choose the site configuration. That configuration supplies the root and request policy.
What is the difference between a DNS record and a virtual host?
The DNS record gives the client a route to an address or another name. The virtual host is a rule at the server that recognizes the requested site and selects how to serve it. Both must agree for a normal public request.
How do you verify an unmatched-host response?
Send one deliberate unmatched hostname to the approved listener and compare its status, body and log with the expected fallback. Identify which address and port group handled it, because different listeners can fall back differently.
Why might an HTTP Host header override be insufficient to test HTTPS?
The TLS connection comes first. The URL name guides the client's handshake name and identity verification. Keep the expected HTTPS URL and override only its destination address, then check the resulting certificate and HTTP response.
Does hosting two vhosts create two independently isolated services?
Separate virtual hosts select different roots and policies within a server process. They may share worker privileges, resources, activation and failure domains. Stronger operational or tenant isolation needs boundaries suitable for the owners and their workloads.
Check your understanding
Both names resolve to the same approved address. What tells the server that the client wants recipes?
Show answer
The request's hostname is matched against the eligible site definitions after selecting the address and port group. The recipes block can then use its own root.
Directly visiting the IP shows orders. Does that prove the recipes vhost is missing?
Show answer
The raw address can select the listener's fallback. Send the recipe hostname to the same address and check its marker and access record.
Both site names appear in the config and both about pages show the same content. Name one reason and the next check.
Show answer
They might share the same root by mistake. Compare the parsed root for each site and the logs from explicit host requests before editing their files.
The trainee changes only recipe about-page bytes inside its active root. Which other site should be tested?
Show answer
Check the identifiable orders route as a control, and ensure your recipe response is served by the recipe block. This catches accidental edits or a shared root.
Can a distinct vhost name by itself protect a private file?
Show answer
A client can supply a host name. Do not place private files in the public root. Use the approved authentication or network access controls for protected resources.
Practise independence between the two sites
Draw both about-page requests with the same destination listener. Label the decision that splits them and the two files that supply their responses.
Run the temporary fixture for a compatible server. Record the three initial markers and what changes after replacing the recipe about file. Repeat with the other engine if it is available.
Prepare an acceptance and rollback note for an orders-only edit. Identify its exact affected files, a recipe control request and the fallback test you would keep.
Revision cards
- Client destination
- The address and port used for the connection. DNS or an explicit override can provide this address.
- Authority
- The HTTP request's intended host information, used among other inputs to select the site.
- Virtual host
- Rules for a selected website, with its own public root and relevant per-site settings.
- Fallback
- The designated or ordered default for the same eligible address and port when the desired name has no match.
- SNI
- A TLS handshake extension that can give the endpoint a requested DNS name before it chooses server credentials.
- Release verification
- Use exact name, path, status and expected content. Check independent sites after a shared configuration action.
Official sources
- Nginx request and default selection
- Nginx server names and precedence
- Nginx listener and root directives
- Nginx configuration lifecycle
- Apache name-based virtual hosts
- Apache address and name matching details
- Apache binding to addresses and ports
- Apache core configuration parameters
- HTTP authority, Host and request semantics
- TLS Server Name Indication
- TLS service identity verification
- Reserved example and test names
- Amazon EC2 Elastic IP addresses
- DNS record types in Route 53
- Curl URL and destination overrides