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

Chapter 6: Web Servers — Nginx and Apache

AWS Cloud

6.7 Understanding the configuration files

Friends, a config file is the set of instructions given to the web server. First see which block does what. Then follow a class request from its site name to the file the server opens.

Nginx structure

# /etc/nginx/nginx.conf (simplified)
user nginx;                        # www-data on Ubuntu
worker_processes auto;             # let Nginx choose the number of workers
events { worker_connections 1024; }
http {
    include       /etc/nginx/mime.types;
    access_log    /var/log/nginx/access.log;
    sendfile      on;
    include /etc/nginx/conf.d/*.conf;        # your site files
    # Ubuntu also has: include /etc/nginx/sites-enabled/*;

    server {                               # sample fallback when this listener marks it as default
        listen       80 default_server;
        server_name  _; # placeholder, not a wildcard
        root         /usr/share/nginx/html;
        location / { try_files $uri $uri/ =404; }
    }
}

Apache structure

# /etc/httpd/conf/httpd.conf (AL2023/CentOS, simplified)
Listen 80
User apache
Group apache
DocumentRoot "/var/www/html"
<Directory "/var/www/html">
    Options Indexes FollowSymLinks
    # grant only the override categories or directives the site needs
    AllowOverride None
    Require all granted
</Directory>
ErrorLog "logs/error_log"
IncludeOptional conf.d/*.conf

Ravindra Bagale's Tip

Use nginx -t for the configuration your service actually reads, then follow its approved reload procedure. Check the named site after the reload. On Apache, run the package’s apachectl configtest or apache2ctl configtest wrapper for the intended instance.

Ravindra Bagale's Tip

Many students write a comment at the end of a line in Apache config, like AllowOverride None # no htaccess – and Apache won't start. In Apache, always put a comment on its own line starting with #. In Nginx, end a simple directive with ; and close a block with its matching brace.

Going deeper

Trace one request through the listener, selected site and location. The lab below shows how two valid mapping directives construct different file paths.

Lab

Chala, use the private lab below to compare the included class site with the fallback site. If you have permission to read a packaged configuration, locate the include that reaches the site file and record the context around it.

Follow a request through the configuration

Imagine a training centre that publishes a class timetable and a printable handout. The timetable lives with the web pages for that course. The same handout belongs to several courses, so the centre keeps the approved copy in a separate shared folder on the server. A student should neither need to know the server folder names nor see every file in the shared folder. The web server configuration connects a visit such as /downloads/handout.txt to the one file the centre intends to publish. Moving the file, changing the public address, or changing who can read it are three distinct decisions.

A configuration file is structured text the server reads to decide what to do. A directive is an instruction, usually expressed as a name and one or more values. A block or section groups instructions so they apply in the right place. Reading a single line such as root /srv/training/site; tells you very little until you find its enclosing block. It might set the base for an entire website, or just for one path in that website. A matching block elsewhere can also affect the final route. Start with the request you want to understand and trace the decisions that are relevant to it.

Write down four facts before reading the configuration. Which address and port did the connection reach? Which website name did the client ask for? Which path did the client request? What response should demonstrate that the correct file or application answered? The address and port decide where the connection arrives. The name may distinguish websites sharing that listener. The path can select a folder, another handler, or a redirect within that site. The response gives you a way to check the story with evidence.

For example, suppose the class visit is http://classes.example.test/downloads/handout.txt. The browser needs an address for that name. It opens a connection on the HTTP port, sends the host and path, and receives an HTTP status and usually a body. In our local practice we connect directly to a loopback address and supply the training hostname as a header. That lets us investigate the web server's decision without creating a DNS record. An ordinary HTTPS visit also negotiates TLS before sending the HTTP request. The hostname can matter there as well because the server needs to offer an appropriate certificate during the handshake.

At the end of the trace, separate three kinds of evidence in your notebook. The configuration text says what a file on disk declares. A successful configuration test says the parser could process that selected configuration and perform the checks it knows about. A request made after a controlled apply says what the running server actually returned. A timetable can still show yesterday's marker if you edited an inactive file, tested the wrong configuration, or hit a different website. Keep these observations separate and the next diagnostic step usually becomes clearer.

Read the Nginx block structure as an outline

Nginx uses braces for blocks and a semicolon after a simple directive. At the top level, commonly called the main context, it can accept directives concerned with the whole process, such as where the primary process records its PID. The events block contains connection handling settings for workers. The http block contains settings for HTTP and can contain one or more server blocks. Each HTTP server block describes a site or a group of names that should behave together. It can contain location blocks that divide paths among different handlers.

# An outline for reading, not a replacement for a packaged config
worker_processes 1;
events {
    worker_connections 64;
}
http {
    server {
        listen 127.0.0.1:8080;
        server_name classes.example.test;
        root /srv/training/site;
        location / {
            try_files $uri $uri/ =404;
        }
    }
}

Draw a box around everything from server { to its matching brace. You can now see that the name, listener, document root and location belong to the same server. Read location / as a broad URI prefix, then read the file test in its own braces. A broad location can coexist with a more specific one. For a first exercise, use simple prefix locations and understand which prefix wins before adding regular expressions. A regular expression is a pattern that describes a family of paths, and using one changes the selection analysis. The exact and regular-expression rules are in the reference when you encounter a real file that uses them.

A directive has an allowed context. A site listener belongs inside an HTTP server block, while a setting that controls workers is applied at the wider process level. Changing indentation may make the code nicer to read, but the parser uses the actual delimiters to establish context. When it says a directive is not allowed here, start by checking the intended enclosing block and any missing braces just above the reported line. A missing delimiter can make a later, otherwise sensible directive appear to be in the wrong place.

Some settings inherit from an enclosing context when no value is defined more specifically. For the lesson example, a root at server level provides the starting directory for locations that use that root. Setting a root in a particular location can produce a different filesystem lookup for only that location. Do not generalize this to an assumption that every child setting merges or accumulates all parent settings. A module documents which contexts are accepted and how its particular directives behave. When a location seems to ignore a server-wide rule, look for a more specific value and check that directive's documentation.

Worker processes actually handle the requests. Seeing worker_connections 1024 under events does not promise 1,024 students can reliably use the site at the same instant. A worker may have connections to clients or to backends, open file limits also matter, and one browser can make more than one request. In an introductory configuration read, record the setting's level and purpose. Performance tuning comes later with measurements of realistic requests and process resources. It would be a poor response to a wrong handout path to increase a connection number before testing the path.

Establish the difference between a parser comment and a decision. An Nginx comment that starts with a hash explains text to the human reader and simple directives still end with semicolons. The block's closing brace takes care of its own structure. Examples in a lesson can show both conventions in a compact form. Apache generally requires comments on their own instruction lines. Copy the idea between servers where it applies, then write it in that server's syntax. Even familiar words such as root and host can refer to different directives in the two programs.

Find the file the service actually reads

A packaged configuration is usually spread across several files. The entry configuration might have core process settings, an HTTP section and a reference to a collection of site files. An include asks the parser to read the referenced file or matching pattern at that point. A folder called conf.d therefore has meaning because the running installation points to it. A file can exist in the expected folder and still be irrelevant if the service chooses an alternate entry point, the include has a different pattern, or a distribution's enabled-sites link has not been added.

Read includes as if their contents were placed where they are called. If an HTTP block includes a file containing a whole server block, that can be a sensible layout. A file that already includes its own http block may be invalid at that same insertion point. The file extension is useful for the glob, but the enclosing context governs legal directives. Copying an entire example with events and http into a site include can therefore fail even if the example would be valid as a standalone configuration.

The entry file path used by a binary has a compiled default, and the service can choose a different path with a startup option. A structured inspection begins by confirming the actual service invocation, the intended site file and the include that reaches it. In a conventional Nginx installation, operators can use nginx -t to check the configuration selected by that invocation and nginx -T to check and dump configuration files. For a package-managed Apache deployment, appropriate package tooling can perform the config test and the virtual-host dump in its normal environment. These outputs can include private directions, internal hostnames or secrets embedded in configuration. Review them in an authorized shell and share only the necessary redacted lines.

Patterns are a reason to keep backups out of live include directories. A location that loads every *.conf file may read both classes.conf and an old copy named classes-backup.conf. Two definitions can cause a parser error, a warning about an ignored name, or a changed default site depending on what is duplicated. Keep backups in a separate location you can identify and restore deliberately. Ask which copy would be read before assuming a backup is inactive. Changing only the filename inside an enabled folder can leave an unintended duplicate active if the include pattern still matches it.

On a distribution that uses a directory for available sites and a separate linked directory for enabled sites, a symbolic link is a filesystem pointer. Creating it can make a file eligible for inclusion the next time the configuration is read. It does not by itself change the configuration held by the current workers. Verify that the entry config includes the enabled directory, that the link points to the intended file, and that the intended apply and response checks complete. A reader who learns these three checks can reason about a distribution with different directory names as well.

Suppose the published site continues to show the older timetable after you saved a new configuration file. You identify that the service reads one entry file, but the example you followed invoked the executable with another. Both files can pass validation. Neither validation confirms that your chosen running service adopted the change. Compare the command line and selected path, read the relevant include, then make one request that distinguishes the expected new site from the old one. A distinctive marker in a harmless practice file is much better evidence than repeating a screenshot of a page that looks almost the same.

Predict the disk path before sending the request

In the class website, the URL namespace and the server's filesystem are separate. A public URL path is what a student asks for. A disk path is where the program attempts to locate a file while handling that request. With a simple Nginx root mapping, the selected root is combined with the URI path. If the root is /srv/training/site, then /materials/handout.txt maps to /srv/training/site/materials/handout.txt. The directory name materials stays in the calculation.

With an alias inside a prefix location, the matched part of the URL path is replaced with the configured path. In a location matching /downloads/ with an alias of /srv/training/shared/, the remainder handout.txt is attached to that shared filesystem directory. The resulting path is /srv/training/shared/handout.txt. If you put a root set to the shared directory in the same location instead, the public downloads segment would still be appended and you would normally have to create a corresponding subdirectory. Write out both computations once before choosing which spelling serves your goal.

location /materials/ {
    root /srv/training/site;
}
location /downloads/ {
    alias /srv/training/shared/;
}

The trailing slash in this paired prefix and alias is deliberate. It keeps the boundary between the directory and the unconsumed path clear. For this example, leave directory handling outside the experiment and request the full filename. Do not guess that a visit to the bare prefix without a slash behaves the same way as a visit to a named file inside it. Directory indexes, directory redirects, exact locations and other rules can answer those separate requests. Compare the exact path you sent to the exact prefix you intended.

Putting a file in a web directory does not create the public URL you have in mind. The request has to reach the appropriate site and location. Then the selected filesystem mapping, access rules and permissions must permit the worker to read the content. If you have placed a file under shared/ and get a 404 for a simple static request, calculate the requested path before copying it again. The server error log may show an attempted open on an unintended folder. That is useful evidence that the selected mapping differed from your prediction. A permission-denied line is a different clue, as you saw in the CentOS Stream exercise.

Conversely, a successful status can hide the wrong mapping. If two files have the same training handout name in different directories, make their test content visibly different. Request /materials/handout.txt and /downloads/handout.txt and compare the actual body as well as the status. A 200 with the marker for an unapproved draft is a deployment failure for this lesson. A 404 for an intentionally absent name is a success. The written expected results should capture those distinctions, otherwise a browser that simply shows a page gives the team false confidence.

Understand the directory index step

When a request path refers to a directory, the web server can be configured to try a known filename as the document to show. An index is such a default file. A student can open the class homepage using a trailing slash while the server reads index.html. The content remains a file, and its selected name can be changed by configuration. Index lookup can also lead to an internal change of URI and another location decision in Nginx. That is worth remembering when an index behaves differently from a fully named file in a large configuration.

For a simple request for /materials/handout.txt, no directory default is needed. This makes named files a good starting point when learning how mapping works. Once they work, ask what should happen on a bare directory visit. It could display a landing page, return a denial where listing and indexes are unavailable, or intentionally redirect to another public address. Each outcome is a policy choice and should be checked with the exact site and path. Apache uses a DirectoryIndex directive for its index candidate names. Its directory listing feature depends on separate settings, including whether an appropriate module and the Indexes option allow listing.

Consider a class instructor who wants new students to see only the current handout. Enabling a directory listing to avoid writing a one-line page can reveal old material and filenames that were never meant as links. Disabling a listing also does not stop a user from requesting a matching known filename that remains accessible. Stage only approved public files in the directories that are mapped, and give students a deliberate landing page where it helps them find the right material. Configuration and the choice of files both participate in the result.

A quick site review can record the expected outcomes as a tiny route table. The course homepage should return a clearly labeled index. The current material URL should return the published handout. The shared download path should return the shared copy. A wrong site name should take the agreed fallback. An absent filename should yield the normal missing-file status and a log clue. This route table is small enough to write by hand and concrete enough for a colleague to test.

Find the equivalent decisions in Apache

Apache configuration uses a directive per line and named section containers such as <VirtualHost> and <Directory>. A listener tells the program which local address and port to bind. A virtual host tells it which rules to use when handling an eligible connection and name. Keep these jobs distinct. Adding <VirtualHost *:8080> gives Apache a rule for requests received on that port. It does not cause Apache to open that port. There must also be a matching Listen arrangement appropriate to the server. The example below deliberately shows both.

# Structure example for an existing authorized Apache test instance
Listen 127.0.0.1:8080
<VirtualHost 127.0.0.1:8080>
    ServerName classes.example.test
    DocumentRoot "/srv/training/site"
    <Directory "/srv/training/site">
        AllowOverride None
        Require all granted
    </Directory>
</VirtualHost>

Here the virtual host associates the name and documents. DocumentRoot supplies the base directory for ordinary file mapping. The directory container describes access to a path on the server's filesystem, and the indicated access rule applies there. A <Location> section, by comparison, addresses a URL space. A public path can be handled by a module without any corresponding regular file, so URL-based handling may be necessary in its own right. When a file is served under more than one permitted public path, a filesystem section is appropriate for a rule that should follow the file. Apache documents the ordering and merging of these containers. Do not assume one simply overwrites the other in the visual order of the file.

ServerName is the canonical name of a site in that configuration. ServerAlias can supply extra names intended to reach it. If several virtual hosts share the same eligible IP and port combination, Apache compares the request's name with the names it knows for that set. A request with no matching name can use the first virtual host for that address and port combination. Treat the default site as a real design choice when the address serves more than one website. An IP-only browser check can consequently show a valid service and the wrong website for the class domain.

A package can place module-loading directives, environment settings and site configuration in separate locations. A standalone excerpt omits those dependencies. Before reusing a directive, check whether the relevant module is built into or loaded by the server and whether the directive is allowed in its section. For example, the directory access rule relies on Apache authorization support and a directory index rule relies on its index configuration. The prior Apache comparison lesson exercises an allowed per-directory override in a separate instance. Here focus on the decision of whether that kind of override belongs in your scheme at all.

AllowOverride None avoids applying per-directory override files for that directory scope. If your deployment intentionally delegates a limited instruction, Apache lets you choose an appropriate override category or explicitly allowed directives. Turning on every category to solve one missing change can give site authors far more control than they need. When a file in .htaccess appears to have no effect, trace the relevant directory rule and module first. Moving every check into the file or turning on broad permissions may mask the actual missing configuration and change behavior outside the original request.

Notice the two syntax patterns as you compare a real Nginx and Apache installation. Nginx puts an HTTP server and its locations in braces. Apache groups virtual hosts and directory or URL sections with named tags, with the listening directive separate. Both can serve the same PDF at the same URL. Translating the decision tree is more useful than mechanically replacing directive names. Identify the listener, the host rule, the path route, the actual file, and the permissions that allow the worker to return it. Then choose the correct syntax for the program running on that machine.

Lab with two ways to serve the same filename

You will create a separate Nginx instance using your ordinary account, a new scratch directory and one loopback port. It will give the class's ordinary handout and the approved shared handout different text markers. Choose a disposable Linux learning machine that already has Bash, Python 3, curl and Nginx with support for the separate error-log option used below. Open a fresh Bash session and work through the blocks in the same session. If the first block cannot prepare the directory and print a port, use the path worksheet below. None of the examples require another website, name registration, an inbound firewall rule or a service-manager command.

unset layout_lab layout_port layout_url
if [ "$(id -u)" -ne 0 ] && command -v python3 > /dev/null &&
   command -v curl > /dev/null && nginx -e stderr -h > /dev/null 2>&1; then
  layout_lab=$(mktemp -d "$HOME/nginx-layout.XXXXXXXX") &&
    cd -- "$layout_lab" && mkdir -p ./site/materials ./shared ./sites &&
    printf '%s\n' 'Class timetable index' > ./site/index.txt &&
    printf '%s\n' 'Course-specific handout' > ./site/materials/handout.txt &&
    printf '%s\n' 'Approved shared handout' > ./shared/handout.txt && pwd
  layout_port=$(python3 -c 'import socket; s=socket.socket(); s.bind(("127.0.0.1",0)); print(s.getsockname()[1]); s.close()')
  printf 'Practice port %s\n' "$layout_port"
fi

The operating system supplies an available port for the temporary probe. The web server binds it separately a moment later, so a race is possible. If the start reports an address already in use, do not stop the process that holds it. Inspect your private logs, remove only the generated files after confirming no private master remains, and start with a fresh scratch directory. The generated directory should sit in your home folder, and you should see one numeric port. Each marker file is deliberately short so you can compare the observed content directly with the worksheet.

The entry file below has main, events and HTTP contexts. The first HTTP server is a deliberately recognizable fallback, and the file linked from the HTTP context defines a second complete server. The quoted paths are created from your scratch directory. There is no system document root in either server. Read the two course handout locations and predict how each one constructs a file path. The third location is a deliberate faulty mapping to study a 404 from a config that parses successfully.

if [ -n "$layout_lab" ] && [ -n "$layout_port" ] &&
   [ "$(pwd -P)" = "$(cd -- "$layout_lab" && pwd -P)" ] &&
   [ -f ./site/materials/handout.txt ] && [ -f ./shared/handout.txt ]; then
  cat > ./nginx.conf <<EOF
worker_processes 1;
pid "$layout_lab/nginx.pid";
error_log "$layout_lab/error.log" notice;
events { worker_connections 32; }
http {
    access_log "$layout_lab/access.log";
    client_body_temp_path "$layout_lab/body";
    proxy_temp_path "$layout_lab/proxy";
    fastcgi_temp_path "$layout_lab/fastcgi";
    uwsgi_temp_path "$layout_lab/uwsgi";
    scgi_temp_path "$layout_lab/scgi";
    default_type text/plain;
    server {
        listen 127.0.0.1:$layout_port default_server;
        return 200 "Practice fallback";
    }
    include "$layout_lab/sites/*.conf";
}
EOF
  cat > ./sites/classes.conf <<EOF
server {
    listen 127.0.0.1:$layout_port;
    server_name classes.example.test;
    root "$layout_lab/site";
    index index.txt;
    location /materials/ {
        root "$layout_lab/site";
    }
    location /downloads/ {
        alias "$layout_lab/shared/";
    }
    location /wrong/ {
        root "$layout_lab/shared";
    }
}
EOF
  layout_nginx=(nginx -p "$layout_lab/" -c "$layout_lab/nginx.conf" -e "$layout_lab/bootstrap.log")
  if [ ! -s ./nginx.pid ] && "${layout_nginx[@]}" -t && "${layout_nginx[@]}"; then
    for layout_attempt in {1..20}; do
      [ -s ./nginx.pid ] && break
      sleep 0.1
    done
    [ -s ./nginx.pid ] && layout_url="http://127.0.0.1:$layout_port"
  fi
fi

The test should say the named configuration syntax is acceptable and the test succeeded. The private master then starts using the same invocation. It writes a numeric PID to its own file, which the shell waits for briefly. The root directive under /materials/ repeats the server-level value on purpose to make the arithmetic easy to see. A normal deployment would need a separate location there only when it has an additional instruction or more specific setting. The root under /wrong/ is syntactically legal but names a base that has no corresponding wrong subfolder.

if [ -n "$layout_url" ] && [ -n "$layout_lab" ] &&
   [ "$(pwd -P)" = "$(cd -- "$layout_lab" && pwd -P)" ] && [ -s ./nginx.pid ]; then
  curl --noproxy 127.0.0.1 -fsS --max-time 5 -w '\nUnknown host HTTP %{http_code}\n' "$layout_url/"
  for layout_path in / /materials/handout.txt /downloads/handout.txt; do
    printf 'Named site request %s\n' "$layout_path"
    curl --noproxy 127.0.0.1 -fsS --max-time 5 -H 'Host: classes.example.test' \
      -w 'HTTP %{http_code}\n' "$layout_url$layout_path"
  done
  curl --noproxy 127.0.0.1 -sS --max-time 5 -H 'Host: classes.example.test' -o /dev/null \
    -w 'Wrong mapping HTTP %{http_code}\n' "$layout_url/wrong/handout.txt"
  tail -n 5 ./access.log
  grep -F 'shared/wrong/handout.txt' ./error.log
fi

The first visit should say Practice fallback and show 200. The connection still went to the same port as the subsequent requests. The only important new fact when you add the training hostname is the HTTP site selection. The home request should return Class timetable index, the materials request Course-specific handout, and the downloads request Approved shared handout. All three should be 200. A different marker gives you a more precise clue than the status alone. For example, seeing the fallback on all three tests would lead you back to the header, server name or included config before you investigated missing files.

The deliberate wrong mapping returns 404. Read the log line immediately below. It should include the scratch pathname ending in shared/wrong/handout.txt. The approved shared handout stayed in shared/handout.txt. The extra piece wrong appeared because root adds the request URI. Both mappings passed the same parser test and were active in the same server. You have just proved that a mapping can be valid configuration and still contradict the intended public-to-disk route. The relevant fix would be mapping that path differently or removing the unintended route, according to the site's goal. Creating a random folder to silence the log would leave the goal unexamined.

Use the five responses to compare first-page checks with route coverage. The homepage proves the site's docroot and index for one request, while the shared handout proves a different rule for one file. The missing case guards a failure that often escapes testing when everything is expected to succeed. In a practical handoff, write the expected markers before opening the browser. Store them alongside the name and path so colleagues can repeat the test when changing an include or moving a directory. For a real HTML page, checking one linked stylesheet or image can catch a mapping problem a homepage body would miss.

End the private server and hand back the evidence

Shut down with the same configuration and prefix that started this master. The private PID file should disappear when the master exits. If the file remains after the brief wait, inspect the private log and process identity before taking any further step. Do not delete its files while it is active. The removal below asks about each expected file and removes only empty known directories. Answer positively after checking the current practice directory and the file list. An unrelated file in that directory will cause the final empty-directory removal to fail, leaving it for you to inspect.

if [ -n "$layout_lab" ] &&
   [ "$(pwd -P)" = "$(cd -- "$layout_lab" && pwd -P)" ] &&
   [ -s ./nginx.pid ]; then
  "${layout_nginx[@]}" -s quit
  for layout_attempt in {1..30}; do
    [ ! -e ./nginx.pid ] && break
    sleep 0.1
  done
fi
if [ -n "$layout_url" ] && [ -n "$layout_lab" ] &&
   [ "$(pwd -P)" = "$(cd -- "$layout_lab" && pwd -P)" ] && [ ! -e ./nginx.pid ]; then
  ls -la -- . ./site ./site/materials ./shared ./sites
  rm -i -- ./nginx.conf ./sites/classes.conf ./bootstrap.log ./error.log ./access.log \
    ./site/index.txt ./site/materials/handout.txt ./shared/handout.txt &&
    rmdir -- ./site/materials ./site ./shared ./sites ./body ./proxy ./fastcgi ./uwsgi ./scgi &&
    cd -- "$HOME" && rmdir -- "$layout_lab"
fi

Your written handoff needs three observations. First, record which new file was included and the context from which it was included. Second, state which input changed the default response to the course marker. Third, show the full attempted path that explains the intentionally wrong route. A colleague should be able to read the handoff and apply the same reasoning to a renamed course next month without opening your old terminal. Reproducing the result is often more useful than keeping a large directory of practice data.

If you could not run the instance, complete the same worksheet by hand. Draw an outer HTTP box with both server blocks. Point a first arrow labeled IP and port to the two site definitions. Point a second arrow labeled request name to the course site, and a separate arrow for the unmatched name to the default. Under the course site, list each test URI, selected mapping directive, resulting filesystem path and intended result. For the root rule below the wrong prefix, write the extra directory name explicitly. Then compare your predictions to the expected lab results. This checks the core reasoning even when the binary is unavailable.

As a follow-up design task, propose a separate site configuration for the same training centre when it adds a weekend class. The new hostname should show a different home marker and share the approved handout file. Your design should name the existing listener, the new host value and the shared location. Explain which permissions allow both workers to read the same directory if they run under the same account. If the weekend course needs different access rules or its own service account, record that as an additional requirement. A new server name by itself does not guarantee OS-level separation between courses.

Explain a route in an interview

How would you approach an unfamiliar Nginx configuration that spans a dozen files?

I would begin with a single example request and the active service entry configuration. I would confirm which local address and port the connection reaches, then read the matching server definitions and identify how the name selects one of them. From within that site I would examine the locations that match the path and the directive that serves or forwards it. At each include I would record the context where the extra file is read. Finally I would compare a controlled request and relevant log entry against my predicted result. I could explain why one line mattered in the chosen route without trying to memorize the entire hierarchy.

Why did a valid root rule fail to serve the handout under the intended path?

The Nginx root directive uses a configured base and appends the request URI. The operator had placed the file directly in the shared directory. The rule instead looked for a subdirectory corresponding to the public prefix. The error log showed the extra path component. I would check which disk layout the team actually wants. If the public name is independent of the shared folder's name, a correctly scoped alias can map it directly. A fixed path prediction and a new request with a visible test marker would demonstrate the intended result.

What is the practical difference between a port in Apache Listen and a port in VirtualHost?

The first makes the server open an address and port. The second describes which existing connections are eligible for a group of website rules. A virtual host for port 8080 may be present and pass a configuration parse while the server listens only on port 80. Check the live listener first, then see whether the address, port and request name select the intended virtual host. If the port is absent, editing the document root cannot make the TCP connection work. When a listener is present but the wrong default responds, name selection is a better place to investigate.

Which Apache container would you use to reason about permissions for a filesystem directory?

I would start with the directory container for the real path on the server. A URL location container answers a question about a place in the public URL namespace, which can be mapped before, during or after other handling. A file may be reachable through more than one URL, and a proxied URL may have no local file at all. To diagnose a refusal, I would identify the selected virtual host, compute the real path if there is one, and inspect the applicable authorization directives in the correct merge order. I would also distinguish Apache authorization from the operating system's file access rules.

How do you check whether a file in conf.d is live?

I verify where the running service starts and find an include matching that file. Then I check the same effective configuration the service would load, including the scope and any linked paths. That explains eligibility. If the expected change has been applied through an authorized process, I send a request whose response differs from the old one and check the correct log. Seeing the path in a loaded file list or in a configuration dump is useful, but a request can still select another host or location. It is the combination of inclusion, apply and request evidence that lets me say which file matters.

Why is a successful syntax check followed by a named request?

The syntax check validates the candidate text and performs supported checks such as opening referenced files. It cannot infer that Approved shared handout is the content the class centre wants. Two acceptable root values might serve two different valid pages. A named request holds the connection destination steady while choosing the actual intended site. After application I check the route, its status and a distinctive body marker. If an unexpected fallback responds with 200, I can diagnose name matching without confusing it with a port failure or assuming every successful status is equivalent.

Predict the next observation

  1. Inside an Nginx HTTP block an include reads a file that begins with another HTTP block. The directive reports that HTTP is not allowed there. A student suggests renaming the file to use a different extension. What should they check first?

    Answer and reasoning

    Check the context at the include and the contents the parser receives there. Put eligible server-level content in the file included from the outer HTTP section, or use the entire original example as a separate entry configuration if its dependencies are correct. Changing an extension may make the pattern skip the file, but skipping is different from including the intended settings in the right scope.

  2. A server-level root points to the course folder. A specific materials location sets its own root to the archive. What file would a request for the materials handout normally look up?

    Answer and reasoning

    Under those simple prefix rules, the more specific location selects the archive base and the URI supplies the materials directory and filename. Calculate the full archived path, then inspect it with a named request. If a different location or an internal redirect applies, resume the trace there. Reading the wider root alone would miss the more specific path setting.

  3. On the lab port, one request shows the practice fallback. A request with the training host on the same port shows the timetable. Which part of the request changed the result?

    Answer and reasoning

    The hostname in the HTTP request changed. Both requests reached the same local address, port and server process. The second selected the classes server while the first used the explicitly marked default. This is evidence for host-based selection in an unencrypted local request. It does not by itself check public DNS or any TLS certificate.

  4. After moving the class handout, the old URL returns 404 and the error log reports an extra downloads folder in the pathname. Which mapping would produce that extra component?

    Answer and reasoning

    A root rule using the shared directory would append the whole request URI, including downloads. The alias shown in the lab replaces the matching public prefix and looks for the named file directly under the configured shared directory. Examining the filesystem pathname with the requested URL explains the difference without a trial-and-error series of service restarts.

  5. The Apache service is listening and an eligible virtual host uses one root, but the browser shows the contents of a different virtual host. What two tests would give better evidence than restarting?

    Answer and reasoning

    Use Apache's virtual-host configuration dump through the package's correct wrapper and a request with the intended HTTP hostname. The first checks which hosts are defined for the eligible socket and their ordering. The second shows the runtime response when the expected name is supplied. Confirm the address and port first so those observations describe the same service.

Cards for the next configuration review

Listener then site then route

Start at the socket that receives the request. Decide which site serves that name on the listener. Use the path to choose the route within that selected site.

Two different path calculations

A root adds the URI to the base. A prefix alias replaces the matched URL prefix with its configured disk path. Use a full sample filename to catch an extra directory.

An include has a location in the outline

A separate file is interpreted in the context of the include. Check the matching pattern and the actual entry configuration before judging whether the file can matter.

Two results with the same 200

A fallback and the named site can each return 200. A distinctive marker and an accurate host request identify which site actually returned the body.

Evidence from three moments

Read the candidate. Test the same effective configuration. Observe the correct response after applying it. Write down what each step confirmed for the next learner.

Official references