Chapter 8: Configuring Nginx and Apache
Friends, in Chapter 6 we installed Nginx and Apache, and in Chapter 7 we hosted our first sites by copy-pasting a server block. That was enough to get started, but in real projects you will be asked to change things – move the website to another folder, run it on another port, host three sites on one server, redirect www or hide the version number. Mauli Dairy, Pune (a fictional business, only for learning) now wants an admin panel and a blog along with the order site. In this chapter we open the config files and understand them line by line. Once you can read a config file comfortably, you will handle web servers with confidence. Come on, let's start!
मित्रांनो, Chapter 6 मध्ये आपण Nginx आणि Apache इन्स्टॉल केले, आणि Chapter 7 मध्ये server ब्लॉक कॉपी-पेस्ट करून पहिल्या साइट्स होस्ट केल्या. सुरुवातीला इतकं पुरेसं होतं, पण खऱ्या प्रोजेक्ट्समध्ये तुम्हाला गोष्टी बदलायला सांगतात – वेबसाइट दुसऱ्या फोल्डरमध्ये न्यायची, दुसऱ्या पोर्टवर चालवायची, एकाच सर्व्हरवर तीन साइट्स, www redirect किंवा व्हर्जन नंबर लपवायचा. Mauli Dairy, Pune (काल्पनिक बिझनेस, फक्त शिकण्यासाठी) ला आता ऑर्डर साइटसोबत एक ॲडमिन पॅनल आणि ब्लॉग पण पाहिजे. या चॅप्टरमध्ये कॉन्फिग फाइल्स उघडून लाइन बाय लाइन समजून घेऊ. कॉन्फिग फाइल आरामात वाचता आली की वेब सर्व्हर्स कॉन्फिडन्सने हँडल कराल. चला, सुरू करूया!
दोस्तों, Chapter 6 में हमने Nginx और Apache इंस्टॉल किए, और Chapter 7 में server ब्लॉक कॉपी-पेस्ट करके पहली साइट्स होस्ट कीं. शुरुआत के लिए इतना काफ़ी था, लेकिन असली प्रोजेक्ट्स में आपसे चीज़ें बदलने को कहा जाता है – वेबसाइट दूसरे फ़ोल्डर में ले जाना, दूसरे पोर्ट पर चलाना, एक ही सर्वर पर तीन साइट्स, www redirect या वर्ज़न नंबर छुपाना. Mauli Dairy, Pune (काल्पनिक बिज़नेस, सिर्फ़ सीखने के लिए) को अब ऑर्डर साइट के साथ एक एडमिन पैनल और ब्लॉग भी चाहिए. इस चैप्टर में कॉन्फ़िग फ़ाइलें खोलकर लाइन बाय लाइन समझेंगे. कॉन्फ़िग फ़ाइल आराम से पढ़ना आ गया तो वेब सर्वर्स कॉन्फ़िडेंस से हैंडल करोगे. चलो, शुरू करते हैं!
In this chapter
- Where each config file lives
- Reading an Nginx server block
- Reading an Apache virtual host
- Changing the document root
- Running a site on another port
- Many sites with virtual hosts
- Redirects, versions, uploads
- The safe change workflow
Browser request: GET /about.html Host: site1.example.com (port 80)
|
+---------------------v----------------------+
| 1. Which listen port? listen 80 / Listen 80
| 2. Which site? server_name / ServerName (Host header)
| 3. Which folder? root / DocumentRoot
| 4. Which file? index / DirectoryIndex; URL and filesystem mapping have different scopes
+---------------------+----------------------+
|
/var/www/site1/about.html --> 200 OK
This diagram follows a simple file request. Other handlers can redirect, deny or proxy a request. Read the applicable listener, host and mapping rules, then verify the response.
Concepts in this chapter
- 8.1Where the configuration lives
- 8.2Reading an Nginx configuration
- 8.3Task: change the Nginx document root
- 8.4Reading an Apache configuration
- 8.5Task: change the Apache DocumentRoot
- 8.6Task: run a site on a different port
- 8.7Multiple sites with name-based virtual hosts
- 8.8Useful everyday configurations
- 8.9The safe change workflow
- 8.10Troubleshooting configuration problems
Review and practice
Change one site and verify both sites
Read all steps
- Observed baseline
Record each hostname and its expected response before changing configuration. A successful status alone cannot identify which site answered.
- Scoped candidate
Edit the workshop site file while preserving the library configuration. Keep the backup outside active include patterns and test the selected candidate.
- Applied configuration
Apply the tested configuration to the intended instance. Inspect the reload evidence and use fresh requests to check the resulting behavior.
- Verified recovery
The workshop returns its new marker while the library retains its own marker. Restore the prior workshop file, apply it and verify both responses again.
Translate a requested change into observable behavior
The college workshop website already works, and the library has its own site on the same host. The coordinator now wants the workshop files moved into a new release directory. Later, the workshop team wants a temporary notice page and a redirect from an old URL. These requests sound small, but they affect different parts of web-server configuration. Your first job is to state precisely what should change and what evidence will demonstrate the result.
For the directory move, the requested behavior is that the workshop hostname returns the new workshop release while the library hostname continues to return the library page. The listener need not change. For the temporary notice, one path should return a defined response. For a redirect, the original path should tell the client where to make its next request. Treating all three as “edit the config” hides the distinctions that make verification possible.
Write a change record with five items: the current request, its observed response, the intended new response, the smallest configuration area responsible and the rollback evidence. In a real team, this record helps a reviewer understand the change. In a classroom, it helps you avoid changing a port, a directory and a permission rule simultaneously, then being unable to explain which change caused the result.
The chapter uses both Nginx and Apache because the underlying responsibilities are comparable while their configuration languages differ. Learn the request-handling decisions first, then express them with the correct product's directives. We will keep the practical Nginx experiment in a separate unprivileged loopback instance. The Apache comparison teaches how to inspect and reason about its corresponding configuration without assuming that a snippet is a complete installation.
Find the configuration selected by the actual service
A web-server process does not search every configuration-looking file on the machine. It starts with a selected main file and follows its configured includes. A package can provide a default path, while startup arguments can select another path. Containers and custom installations can differ again. Before editing, identify the service, executable, startup arrangement and configuration path that belong to the site you are investigating.
Nginx provides a test option and an option that also prints the parsed configuration files. When you supply an alternate prefix or configuration, use the same arguments consistently for testing and control. Testing one file and signalling a different instance does not validate the intended change. Our lab deliberately uses an explicit prefix and file so the relationship remains visible in every command.
A printed configuration dump describes what the invoked command reads from disk at that moment. It is not a snapshot of every directive currently held by an already running worker. Someone may have edited a file without applying it, or the running service may have started with different arguments. Compare the invocation, the application event and the observed request behavior. These three pieces distinguish the candidate on disk from the active service.
Apache provides syntax checking and virtual-host inspection through its control tools. Distribution wrappers may establish environment variables and package paths before invoking the executable. Use the package's supported wrapper when inspecting that installation. A direct executable call with a missing environment can produce a misleading failure that the actual service invocation does not have. The Apache command reference describes its switches, and the Nginx command reference describes explicit file and prefix selection.
Configuration dumps can contain sensitive operational details or values embedded by an application team. Review them locally and share only the relevant redacted excerpt when asking for help. For our teaching exercise, every value is fictional and the configuration is small. In a production incident, you still need the complete include relationship, but you do not need to publish an entire server configuration to explain one wrong path.
Treat included files as part of one configuration
An include directive lets a main file load additional configuration. This is useful for separating sites or reusable settings. It does not make each included file an independent running server. A syntax error in a file included by the service can prevent the candidate configuration from passing its test, even if the error belongs to a site different from the one you were thinking about.
Imagine a main Nginx file that includes all files ending in .conf from a sites directory. The workshop file and the library file both enter the same HTTP configuration. A backup named workshop.conf.bak may not match that pattern, while a backup named old-workshop.conf may match it and accidentally load an outdated duplicate. The effect depends on the exact include pattern. Store backups outside active include locations or give them a deliberately excluded arrangement.
A familiar directory name is not enough. A file in sites-available may be a candidate waiting to be enabled by a package convention. A file in sites-enabled affects the service only if the main configuration includes the relevant path. On another package, conf.d may be the expected location. Trace the include statements instead of treating any directory name as a universal activation mechanism.
For each included site file, record the listener, names and content or upstream mapping it contributes. If two files unexpectedly declare the same name on the same listening arrangement, inspect the product's warning and selection behavior. Do not assume the newest filename or latest modification timestamp wins. The loaded configuration and its defined ordering rules determine behavior. The Apache configuration guide explains its include and file conventions.
Read the enclosing context before interpreting a directive
A directive is a configuration instruction. Its context determines where it is permitted and which requests or processes it affects. In Nginx, the main configuration can contain events and HTTP contexts, with server and location contexts inside the HTTP arrangement. In Apache, directives may apply globally, to a virtual host or within particular section types. The same-looking value in two different places can therefore have a different scope.
Suppose the workshop team requests a larger upload allowance for one assignment endpoint. A setting applied at a broad HTTP or global level may affect the library too. A more specific supported context can limit the change to the intended site or request handling. Before choosing the location of a directive, state which requests should receive the new behavior. That requirement should guide the scope.
Inheritance is defined by each directive and module; it is not safe to assume every child block simply adds its values to every parent value. Some settings replace inherited values, and some merge according to particular rules. A configuration can pass syntax checking while an assumption about inheritance is wrong. Read the specific directive reference and verify a representative request at each affected scope.
Version support also matters. A current online reference may document a directive added after the version installed in your lab. Record the installed version and consult the compatibility information before copying a new setting. The right response to an unknown-directive error is to understand the version or module requirement, not to delete unrelated lines until the test happens to pass.
Separate listener selection, website selection and resource handling
Use three decisions to organize a basic request. First, which address and port accept the connection? Second, which site configuration applies to the requested name within that listening arrangement? Third, which handling applies to the requested resource? A document root is only one possible part of the third decision. The server may instead return a fixed response, redirect the client or pass the request to an application.
For our workshop and library, both names share one loopback port in the lab. The names select separate site blocks. Each site has an independently named content directory. If a workshop request returns library content, changing the workshop file's permissions will not repair a site-selection error. Follow the decisions in order and identify where the observed result diverges from the intended one.
A default site handles requests that do not match an intended name under the applicable rules. This is worth designing deliberately. In our lab, an unmatched name gets a clear default response rather than silently displaying the workshop page. That makes mistakes visible. A production default should follow the application's requirements, but accidental fallback to an unrelated site's content should not be mistaken for proof that name-based hosting is working correctly.
The Host header is useful for controlled HTTP testing. It lets us send different intended names to the same local address and port. The returned body then identifies which site answered. This test does not validate public DNS, external reachability or an HTTPS certificate. Record the boundary it covers and use additional checks for the public deployment path. The Nginx server-name guide and Apache virtual-host guide describe name selection.
Predict Nginx path handling with a small decision exercise
The following fragment is for reading. It belongs inside an appropriate server context and is not a complete Nginx configuration. Each matching branch returns a different label, making it possible to observe the selected handling without depending on a filesystem file. Predict the label before you run the later complete lab.
location = /files/special.txt {
return 200 "exact-handler\n";
}
location /files/ {
return 200 "prefix-handler\n";
}
location ~ \.txt$ {
return 200 "regex-handler\n";
}
For the exact special-file path, the exact location wins. For an ordinary path beneath files that does not match the regular expression, the prefix handler is selected. A text-file path without the exact special match can select the regular-expression handler. The point is that a prefix match does not automatically exclude a later applicable regular expression in this simple arrangement. Writing the prefix block above the regex does not make it win every such request.
The simplified exercise uses flat locations and no rewrite-driven internal redirects. More elaborate configurations can add nesting and further processing. Learn the simple case precisely, then inspect the full rules before generalizing. A selected location also does not prove that a corresponding file exists: in this exercise, the return directive supplies a response without reading that named file.
Compare this with an ordinary root mapping. If a server has a root directory and a request is handled as a static resource, you can predict a candidate filesystem path. If a location returns a fixed response, that prediction is not the action being performed. If it proxies to an application, an upstream request is involved instead. Always identify the handler as well as the matching path. The Nginx request-processing guide describes the matching sequence used by the product.
Distinguish Apache filesystem sections from URL sections
Apache Directory sections concern filesystem locations. Location sections concern URL space. These are not interchangeable descriptions of the same thing. A URL may map through an alias, a proxy or another handler, so the web-visible path is not always a simple spelling of the filesystem location. When the requirement is to control access to files in a directory, choose and verify the appropriate filesystem-oriented configuration.
Consider the workshop files under a public directory and the library files under another. A Directory rule can apply to the specific workshop filesystem path. A Location rule for a URL such as notices describes requests in that URL space, which could be served in more than one way. Explain which boundary your requirement concerns before choosing a section. This reduces the chance of granting access more broadly than intended.
Apache combines applicable configuration sections according to its processing and module rules. It is not a simple programming script in which the last visually written line always overrides everything above it. Different section types have a defined merging order, and the meaning of combining directives depends on the relevant module. Keep a minimal configuration while learning, then consult the Apache section-merging documentation when multiple rules overlap.
A VirtualHost declaration also does not create a listening socket on its own. The Listen arrangement must correspond to the intended address and port. DocumentRoot specifies the usual content basis, while directory authorization and filesystem access remain additional considerations. These distinctions explain a common beginner problem: a neatly written virtual-host block can still be unreachable or forbidden because another required piece has not been configured.
Move the content root without losing the site boundary
Before changing the workshop root, prepare the new directory and verify its release marker, index file and assets. Keep the old release available. Record a workshop request and a library request before the change. The desired result is that only the workshop content marker changes. If the library changes too, your modification was broader than the requested site boundary.
Check the serving identity's access to the new path, including parent-directory traversal and any applicable security policy. A path inside an administrator's home directory may not be accessible to the web worker even if the final file is readable. A path copied to a different location may also need the appropriate policy context. Do not respond to a 403 by changing permissions recursively across unrelated directories.
Update the responsible site's root setting, test the candidate and apply it through the intended instance's supported control path. Then request the workshop and library again. Compare their bodies, not just their statuses. Both old and new roots can return 200, so the release marker provides the evidence that the intended content changed. A successful reload alone cannot distinguish those outcomes.
Rollback uses the same discipline. Restore the previous root configuration, test it, apply it and repeat both requests. Recovery means the expected old workshop marker returns while the library still behaves correctly. Keeping a backup without verifying the restoration path leaves part of the exercise unfinished. In the lab below, you will perform this sequence with ordinary local files and a separate process.
Change a port as a connection-path change
A port change affects where clients connect. It is different from moving a directory or changing a hostname. If the workshop moves from one port to another, the request URL, upstream configuration or public entry point may need a corresponding change. A client that still connects to the old port is not testing the new listener, even if its requested hostname remains correct.
For Apache, coordinate the Listen directive and the applicable VirtualHost address-and-port declaration. For Nginx, inspect the selected server's listen directives and other servers sharing those endpoints. Also check whether another process already owns the desired address and port. A bind conflict is not repaired by changing the content directory.
On a real host, network controls and operating-system policy can affect an alternate port. Make only the narrow changes required by the approved design. Opening a port in a security group does not create a listener; starting a listener does not prove a remote path permits it. In our loopback exercises, we deliberately avoid public exposure so you can first learn the server's own behavior.
Write the before and after request explicitly, including scheme, hostname and port. If the client-facing port stays the same because a proxy or load balancer forwards to a changed backend port, draw those two connections separately. This prevents an important ambiguity: the port visible to the visitor and the port used by the application path may be different.
Choose redirects, response limits and headers for a stated reason
A redirect tells the client to request another URL. It is different from internally mapping a URL to another file. In a redirect response, inspect the status and Location header, then verify the destination separately. A working redirect to a broken destination is not a successful migration. Repeated redirects between two URLs form a loop, even if each individual response is syntactically valid.
Temporary and permanent redirects express different intent, and method-preserving codes matter for requests beyond a simple GET. Do not choose a permanent redirect casually while experimenting because clients and intermediaries may retain it. For our local teaching route, a temporary redirect makes the experiment's purpose clear. The Nginx return and rewrite reference and Apache redirect reference explain the corresponding mechanisms.
A request-body limit controls the size of data accepted under the relevant handling. It does not prove that an application will accept or correctly store an uploaded file. An upstream framework or another proxy may impose a different limit. If an assignment upload fails, identify which component rejects it and the actual request size before increasing limits. The request body can include encoding and multipart overhead, so it is not always identical to the size of one file on disk.
Response headers describe behavior to clients, but inheritance and response-status conditions can affect whether a configured header appears. Verify it on the relevant successful and error responses. Similarly, reducing version information in a response may reduce unnecessary disclosure, but it does not patch a vulnerable server or authorize an application operation. Keep maintenance, access control and response presentation as distinct responsibilities.
Review the candidate before applying it
Read a proposed change as a reviewer who did not write it. Which requests are intended to change? Which files contain the change? Does an include pattern load a backup accidentally? Does a shared setting affect both sites? Is the proposed document root actually populated? Can the serving identity reach it? These questions turn the review into a check of behavior, rather than a search for attractive formatting.
Compare the candidate with the known-good configuration. A focused difference is easier to assess than an entire copied configuration with unrelated defaults. If the only requirement is a new workshop root, an unexplained change to listener addresses, logging and body limits deserves investigation. Some changes legitimately require several directives, but each should connect to the requirement.
Run the appropriate test with the same configuration selection used by the intended instance. Read both the result and any warnings. A zero exit status can coexist with a warning that deserves attention, and an error may name a file included by the main configuration rather than the file you initially opened. Follow the reported path and line in the actual candidate.
Apply only after the test passes. Observe the control command and the service's logs, then run the planned request checks. Keep a rollback trigger concrete: wrong workshop marker, unexpected library content, failed required path or a relevant error rate. “It feels different” is not as useful as a reproducible mismatch between expected and observed behavior.
Once a correction passes the affected checks, record the final configuration and outcome. Avoid continuing to change unrelated settings while investigating a solved issue. That makes it harder to attribute the result and can introduce a new problem. Good operational work ends with a clear explanation of the changed behavior, its verification and any remaining limitation.
Build a small request matrix before the change
A useful request matrix is a short table of requests and their expected responses. For this chapter, give each row a hostname, path, method, expected status and expected identifying content. Include the workshop home page, library home page, a missing path, an exact-match path and a redirect destination. This makes the intended behavior concrete enough for another student to reproduce without guessing which page you meant.
Consider two observations: the workshop URL returns HTTP 200, and its body contains the library timetable. The status is successful at the HTTP level, but the site selection is wrong. A test that checks only status would miss this error. Conversely, a deliberately unknown hostname returning the configured 404 is a correct result for that test. Success means the observation matches the requirement; it does not mean every row must return 200.
Record the request method too. A HEAD request asks for response metadata without the normal response content. It can help inspect headers, but it does not demonstrate that a student's browser received the expected page body. Some applications handle methods differently. Use GET when you need to compare delivered content, and test an application operation with the method and input that operation actually uses.
For a redirect, record two rows: the first response from the old address and the response from its destination. Following redirects automatically is convenient, but it can hide the first response that you are trying to understand. Start by inspecting the original status and Location header. Then request the destination and compare its body. If you later add an automated follow-redirect check, retain the separate evidence that identifies where the redirection occurred.
Run the same matrix before and after applying a candidate. Before-change results establish that your assumptions about the current service are correct. After-change results show both the requested difference and the behavior that must stay stable. In our example, the workshop marker changes during a root move, while the library marker stays the same. That second row is essential when two sites share one server process.
During a graceful reload, old and new workers can briefly coexist while existing work finishes. A request made immediately after sending the signal may therefore be insufficient evidence of the final state. Make a fresh request, inspect the reload log and wait for the expected response within a defined short observation period. If the result does not arrive, investigate the candidate and logs; do not report success merely because the signal command returned without an error.
Keep the matrix alongside a concise result record: which candidate was applied, which rows passed, which failed and what was restored if rollback was necessary. This habit scales from a six-row student exercise to a deployment review. It also improves your explanation in an interview because you can describe a complete change with evidence, instead of listing configuration commands without showing their effect.
Lab: run two independent site configurations locally
Use a Linux learning environment with Nginx and curl already installed. The lab creates one separate Nginx instance under your ordinary account. Its files, logs, PID and temporary directories belong to a new practice directory. Its listener binds only to loopback on port 18888. If that port is occupied, select another unused high port consistently rather than stopping an unrelated process. Do not use sudo or a system-wide service command for these lab files.
Create the content directories first. The two workshop releases contain different markers, while the library contains its own marker. These short bodies make it easy to identify which root answered. The markers are evidence for this controlled exercise, not a substitute for checking a real application's complete content.
cfg_lab=$(mktemp -d /tmp/workshop-config.XXXXXX)
mkdir "$cfg_lab/sites" "$cfg_lab/workshop-one" "$cfg_lab/workshop-two" "$cfg_lab/library"
printf 'workshop-release-one\n' > "$cfg_lab/workshop-one/index.txt"
printf 'workshop-release-two\n' > "$cfg_lab/workshop-two/index.txt"
printf 'library-release-one\n' > "$cfg_lab/library/index.txt"
printf 'Configuration lab: %s\n' "$cfg_lab"
The main configuration defines process-level files, a small event configuration, the HTTP settings and an explicit default site. It then includes the site files. The include relationship is part of the exercise: the workshop and library files become part of this one instance's configuration when it is tested or loaded.
cat > "$cfg_lab/nginx.conf" <<EOF
worker_processes 1;
pid $cfg_lab/nginx.pid;
error_log $cfg_lab/error.log notice;
events { worker_connections 32; }
http {
access_log $cfg_lab/access.log combined;
client_body_temp_path $cfg_lab/body;
proxy_temp_path $cfg_lab/proxy;
fastcgi_temp_path $cfg_lab/fastcgi;
uwsgi_temp_path $cfg_lab/uwsgi;
scgi_temp_path $cfg_lab/scgi;
default_type text/plain;
server {
listen 127.0.0.1:18888 default_server;
server_name _;
return 404 "unmatched-site\n";
}
include $cfg_lab/sites/*.conf;
}
EOF
Create the two site files. The workshop file adds the three labelled location handlers and a temporary redirect. The library file only serves its own content root. The names are reserved practice names supplied directly in our HTTP requests; they do not need public DNS records.
cat > "$cfg_lab/sites/workshop.conf" <<EOF
server {
listen 127.0.0.1:18888;
server_name workshop.test;
root $cfg_lab/workshop-one;
index index.txt;
location = /files/special.txt { return 200 "exact-handler\n"; }
location /files/ { return 200 "prefix-handler\n"; }
location ~ \.txt$ { return 200 "regex-handler\n"; }
location = /old { return 302 /notice; }
location = /notice { return 200 "workshop-notice\n"; }
}
EOF
cat > "$cfg_lab/sites/library.conf" <<EOF
server {
listen 127.0.0.1:18888;
server_name library.test;
root $cfg_lab/library;
index index.txt;
}
EOF
nginx -p "$cfg_lab/" -c "$cfg_lab/nginx.conf" -t
Pause here and predict the root request carefully. The workshop uses an index file ending in .txt, and it also has a regular-expression location matching that suffix. Index processing can lead to an internal redirect, so the workshop root may reach the regex handler instead of simply returning the index file. This is an intentional configuration interaction for you to observe. The library has no corresponding regex handler and can serve its text index normally.
Start the lab instance and compare the responses. Do not automatically follow the redirect in the first check; seeing the intermediate response is part of the lesson. Then request the notice destination directly. Each command varies a deliberate input while keeping the local destination controlled.
nginx -p "$cfg_lab/" -c "$cfg_lab/nginx.conf"
curl --noproxy '*' --max-time 5 -i -H 'Host: workshop.test' http://127.0.0.1:18888/
curl --noproxy '*' --max-time 5 -i -H 'Host: library.test' http://127.0.0.1:18888/
curl --noproxy '*' --max-time 5 -i -H 'Host: unknown.test' http://127.0.0.1:18888/
curl --noproxy '*' --max-time 5 -i -H 'Host: workshop.test' http://127.0.0.1:18888/files/other
curl --noproxy '*' --max-time 5 -i -H 'Host: workshop.test' http://127.0.0.1:18888/files/notes.txt
curl --noproxy '*' --max-time 5 -i -H 'Host: workshop.test' http://127.0.0.1:18888/files/special.txt
curl --noproxy '*' --max-time 5 -i -H 'Host: workshop.test' http://127.0.0.1:18888/old
curl --noproxy '*' --max-time 5 -i -H 'Host: workshop.test' http://127.0.0.1:18888/notice
Record the labels from the prefix, regex and exact paths. The unmatched name should produce our deliberate default 404, and the library root should contain the library marker. The old path should return a temporary redirect whose destination is the notice path; the notice request should return its own body. This gives you a request table with several different forms of handling under one local listener.
The unexpected workshop-root label is useful evidence. It demonstrates why reading only the root and index settings was insufficient. Fix the overlap before performing the root-migration exercise: narrow the regex so it concerns only the files path used in our comparison. Save the original file outside the included sites directory first, then make exactly that replacement.
cp "$cfg_lab/sites/workshop.conf" "$cfg_lab/workshop-original.conf"
CFG_LAB="$cfg_lab" python3 - <<'PY'
import os
from pathlib import Path
base = Path(os.environ["CFG_LAB"])
p = base / "sites/workshop.conf"
text = p.read_text()
old = r"location ~ \.txt$"
new = r"location ~ ^/files/.*\.txt$"
assert text.count(old) == 1
p.write_text(text.replace(old, new))
PY
nginx -p "$cfg_lab/" -c "$cfg_lab/nginx.conf" -t
nginx -p "$cfg_lab/" -c "$cfg_lab/nginx.conf" -s reload
After the reload has taken effect, make fresh root requests for both names. The workshop should now serve its first release marker, while the library marker remains the same. The three files-path checks should retain their intended labels. A reload signal does not mean every old worker has already retired, so compare fresh requests and the log if you briefly observe the previous behavior.
Lab: migrate one root, then restore it
Use the corrected workshop configuration as the known-good starting point for this second experiment. Keep its backup outside the active include pattern. The next script changes one specific root path and asserts that it appears exactly once. This makes the intended scope explicit; it does not search and replace every occurrence of a generic directory name across the machine.
cp "$cfg_lab/sites/workshop.conf" "$cfg_lab/workshop-before-move.conf"
CFG_LAB="$cfg_lab" python3 - <<'PY'
import os
from pathlib import Path
base = Path(os.environ["CFG_LAB"])
p = base / "sites/workshop.conf"
text = p.read_text()
old = "root " + str(base / "workshop-one") + ";"
new = "root " + str(base / "workshop-two") + ";"
assert text.count(old) == 1
p.write_text(text.replace(old, new))
PY
nginx -p "$cfg_lab/" -c "$cfg_lab/nginx.conf" -t
nginx -p "$cfg_lab/" -c "$cfg_lab/nginx.conf" -s reload
Once the change is active, request both sites again. Expect the second workshop marker and the original library marker. These two observations demonstrate the requested content move and the neighboring site's retained behavior. Checking only the workshop would leave the second part of the requirement unverified.
curl --noproxy '*' --max-time 5 -i -H 'Host: workshop.test' http://127.0.0.1:18888/
curl --noproxy '*' --max-time 5 -i -H 'Host: library.test' http://127.0.0.1:18888/
Restore the corrected first-release configuration from its backup, test and reload it, then repeat the same two requests. The original overlap experiment's backup has a different name; deliberately choose the backup from immediately before the root move. This distinction demonstrates why backup names and their recorded purpose matter.
cp "$cfg_lab/workshop-before-move.conf" "$cfg_lab/sites/workshop.conf"
nginx -p "$cfg_lab/" -c "$cfg_lab/nginx.conf" -t
nginx -p "$cfg_lab/" -c "$cfg_lab/nginx.conf" -s reload
The restored workshop marker and unchanged library marker complete the rollback evidence. Inspect this lab's logs and stop its dedicated instance using the same explicit configuration selection. Confirm its PID file disappears before later removing the practice directory. Leave the system service and every other Nginx process alone.
tail -n 12 "$cfg_lab/error.log"
nginx -p "$cfg_lab/" -c "$cfg_lab/nginx.conf" -s quit
The experiment deliberately includes a valid but surprising configuration before the correction. That is different from a syntax error. It trains you to predict request handling and verify the response, because a configuration test cannot determine whether a valid regex expresses the site's intended behavior. The Nginx index documentation explains the internal redirect involved.
Read the equivalent Apache change plan
For an Apache version of the workshop and library design, identify the Listen arrangement and two VirtualHost sections. Assign each an explicit ServerName and its own DocumentRoot. Then identify the filesystem Directory configuration that grants the intended read access for each public tree. This is a reasoning exercise until the distribution-specific lesson supplies the complete package setup and required modules.
Suppose the workshop document root moves from its first release directory to a second one. List every relevant reference that must be reviewed: the DocumentRoot, any matching Directory section, aliases that still point elsewhere and the expected log. Do not assume a single text replacement changes every applicable access rule. Predict the workshop and library responses before proposing the edit.
Use the package's syntax checker and virtual-host inspection tool to review the candidate. After applying it in an approved isolated environment, request both names and compare their content markers. The conceptual acceptance criteria are the same as the Nginx lab, even though the directive language and control tools differ. This is how you transfer understanding between products without copying syntax mechanically.
Tasks for a configuration reviewer
- Draw the include tree. Show the lab's main file, included workshop file and included library file. Place both backups outside the active include pattern and explain why their names and locations matter.
- Predict five requests. Use an exact path, a prefix-only path, a regex-matching path, a directory root and an unmatched hostname. Give the expected label and the rule that produces it. Separate matching from file existence.
- Propose a port migration. Write the old and new request URLs and identify the listener, site declaration, client path and network controls that would need review. Keep the public and backend ports distinct if a proxy is present.
- Diagnose a valid but wrong configuration. Explain the initial workshop-root regex result. State why the syntax test passed, which request exposed the mistake and why narrowing the regex repaired the intended behavior.
- Review an upload-limit request. The workshop needs a larger assignment body while the library does not. Identify the intended scope and other possible upstream limits. Define small, acceptable and over-limit test cases without generating large traffic.
- Document rollback. Record the correct backup, restoration command, configuration test and both site responses. Explain why choosing the earlier overlap-experiment backup would restore an already understood problem.
Interview questions with worked answers
How do you establish which configuration a service uses?
I identify the service invocation, executable and selected main file, then trace its includes. I use the appropriate test or inspection command with matching selection arguments. I distinguish the current files on disk from the configuration already applied to running workers, and verify the resulting request behavior after a controlled application event.
Why can a valid Nginx configuration serve an unexpected body?
Syntax validity does not prove intended request selection. In our lab, index processing redirected the workshop root to a text index path, and a broad regex location supplied a label instead. The configuration was valid but the rule overlapped more requests than intended. A targeted request and the matching rules explained the outcome.
What is the difference between Apache Directory and Location?
Directory applies to filesystem paths, while Location applies to URL space. An alias, proxy or other mapping can make those spaces differ. I choose the section according to the boundary the requirement concerns and check the applicable merging rules, rather than assuming the two section names are interchangeable.
How would you verify a document-root change on a shared server?
I record the target site's original marker and a neighboring site's expected response. After reviewing access to the new directory, I change the responsible site setting, test, apply and request both names. The new target marker proves the content move, while the neighboring response checks that the change remained within its intended scope.
Does a redirect response prove the destination is healthy?
No. It proves the responding component instructed the client to request another URL. I inspect the status and destination, then test that destination and check for loops or an unintended method change. The intermediate protocol response and the user's final outcome are separate observations.
Is hiding the server version a substitute for patching?
No. It changes information presented in responses but does not remove vulnerable behavior from the installed software. I treat updates, configuration, access control and monitoring as separate operating responsibilities. A reduced banner may be part of a policy, but it is not evidence that the service is secure.
Check the decisions behind the directives
1. A file sits in a directory called sites-enabled. Must the service read it?
No. The active configuration must include it through the relevant path or pattern. Directory names alone do not determine the running configuration.
2. A return directive supplies 200 for a path. Must a file with that path exist?
No. The handler can generate that response directly. Match the observed behavior to the configured handler before searching the filesystem.
3. A virtual-host declaration names port 8080. Does it always create that listener?
Not by itself in Apache. The Listen arrangement must correspond. Check the product's actual listener and configuration requirements rather than assuming every declaration creates a socket.
4. Does a configuration dump prove all running workers use those exact current files?
No. It shows what that inspection invocation reads. Files may have changed since the service loaded them, or the invocation may select another configuration. Correlate application events and actual requests.
5. The workshop marker changed correctly. Can you skip the library check?
No, because the requirement includes keeping the neighboring site correct. The library request is a small independent check of that scope, not a duplicate of the workshop request.
Revision cards for controlled changes
- Selected configuration
- The main file and includes chosen by the actual invocation. Match inspection and control arguments to the intended instance.
- Directive context
- The allowed and effective scope of a setting. Read its own inheritance and compatibility rules before assuming it combines with nearby settings.
- Request prediction
- Identify the listener, site, matching resource rule and handler. A file path is relevant only when that handling uses it.
- Candidate validation
- Check syntax and referenced resources, then verify intended behavior through requests. Valid syntax can still express the wrong design.
- Change scope
- Verify the requested new behavior and the relevant neighboring behavior. A shared include or broad setting can affect more than one site.
- Rollback evidence
- Select the known-good backup for the specific change, apply it correctly and demonstrate the expected restored responses.
Before moving on, explain the initial root-request surprise from the lab without reading the answer. Then describe the smallest correction and the two-site evidence after migration and rollback. If you can connect those observations to the responsible rules, you are learning configuration as a system of decisions rather than a collection of commands.
Primary references
- Nginx command-line selection and testing
- Nginx configuration and lifecycle
- Nginx request processing
- Nginx server names
- Nginx core directives and body limits
- Nginx index processing
- Nginx returns and redirects
- Nginx headers and inheritance
- Apache configuration files
- Apache inspection options
- Apache configuration sections
- Apache core directives
- Apache virtual-host selection
- Apache mapping and redirects
- Apache configuration application and lifecycle
Practice Tasks
Practice checks run in your browser. They check the answer for this exercise; they do not create resources or connect to your AWS account.
About this scenarioPandharpur Yatra Tours is a travel business in Pandharpur. Vitthal More looks after its IT and cloud work. They count money in INR and run their AWS resources in the ap-south-1 Region. In the tasks below you do real jobs for them using what this lesson teaches. All names, account IDs, IP addresses and numbers are made up for practice.
0 / 12
Easy Restart a service after a change
For this Nginx exercise, apply tested startup configuration through the intended service action. Other systems, including permitted Apache .htaccess overrides, can read some settings during request handling.
Restart the nginx service.
- Find the Linux command that does this job.
- Add the options (like -r or -h) the task needs.
- Add the file names, folders or users in the right order.
- Use sudo if the job changes system files or users. Click Check answer.
Easy Check if a service is running
When a site is down, first check whether the web server process is running.
Show the status of the httpd service.
- Find the Linux command that does this job.
- Add the options (like -r or -h) the task needs.
- Add the file names, folders or users in the right order.
- Use sudo if the job changes system files or users. Click Check answer.
Easy Install a package on Ubuntu
Ubuntu uses apt. Package names differ: on Ubuntu Apache is apache2.
Install the apache2 package on Ubuntu without being asked to confirm.
- Find the Linux command that does this job.
- Add the options (like -r or -h) the task needs.
- Add the file names, folders or users in the right order.
- Use sudo if the job changes system files or users. Click Check answer.
Easy Install a package on Amazon Linux
dnf is the package manager on Amazon Linux 2023. -y answers yes for you.
Install the httpd package on Amazon Linux 2023 without being asked to confirm.
- Find the Linux command that does this job.
- Add the options (like -r or -h) the task needs.
- Add the file names, folders or users in the right order.
- Use sudo if the job changes system files or users. Click Check answer.
Easy Test a website from the server
curl shows whether the web server answers, even before DNS is ready.
Request http://localhost and show only the response headers.
- Find the Linux command that does this job.
- Add the options (like -r or -h) the task needs.
- Add the file names, folders or users in the right order.
- Use sudo if the job changes system files or users. Click Check answer.
Easy Download code from GitHub
git clone obtains a working checkout. Identify and review the publishable output before deploying it.
Clone https://github.com/pandharpuryatra/website.git into the current folder.
- Find the Linux command that does this job.
- Add the options (like -r or -h) the task needs.
- Add the file names, folders or users in the right order.
- Use sudo if the job changes system files or users. Click Check answer.
Medium Test the nginx config
A configuration test catches syntax and some setup errors. Verify the intended request behavior separately after a successful application.
Check the nginx configuration files for errors.
- Find the Linux command that does this job.
- Add the options (like -r or -h) the task needs.
- Add the file names, folders or users in the right order.
- Use sudo if the job changes system files or users. Click Check answer.
Medium Start a service now and at boot
enable makes it start after reboot; --now also starts it right away.
Enable the nginx service and start it immediately, in one command.
- Find the Linux command that does this job.
- Add the options (like -r or -h) the task needs.
- Add the file names, folders or users in the right order.
- Use sudo if the job changes system files or users. Click Check answer.
Medium Open port 80 to the world
This worksheet practices a public HTTP listener. Verify the intended protocol, port, routes and running service; an HTTPS-only design uses its own listener rule.
Allow inbound TCP port 80 from 0.0.0.0/0 on security group sg-02b64222c4b14c3b2.
- Read the task and decide which AWS service it is about.
- Write aws, then the service name, then the operation (the action word).
- Add each needed flag (--name) followed by its value from the task.
- Flags can be in any order. Click Check answer.
Medium CloudFormation: web security group
This worksheet describes an HTTPS listener rule. Network access, TLS and application authorization are separate parts of the design.
Template with an AWS::EC2::SecurityGroup that allows TCP 443 from 0.0.0.0/0. Add a GroupDescription.
- Start from the top-level keys the task names.
- Indent child keys with 2 spaces (no tabs).
- Fill in each property with the value from the task.
- Click Check answer. Key order does not matter.
Medium Create a security group
A security group is the firewall around your instance.
Create a security group named pandharpuryatra-web-sg with description "Web servers" in vpc-0c4222e4f1deadbee.
- Read the task and decide which AWS service it is about.
- Write aws, then the service name, then the operation (the action word).
- Add each needed flag (--name) followed by its value from the task.
- Flags can be in any order. Click Check answer.
Hard Enable an nginx site on Ubuntu
On Ubuntu, a site is enabled by a symbolic link from sites-available to sites-enabled.
Create a symbolic link to /etc/nginx/sites-available/pandharpuryatra inside /etc/nginx/sites-enabled/.
- Find the Linux command that does this job.
- Add the options (like -r or -h) the task needs.
- Add the file names, folders or users in the right order.
- Use sudo if the job changes system files or users. Click Check answer.