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

AWS Cloud

Chapter 6: Web Servers — Nginx and Apache

Hello, friends! So far we have launched an EC2 server and logged in to it. But a server alone does not show a website – for that you need a web server. In this chapter we will install Nginx and Apache, get to know their config files and learn the commands you need every day. The example stays the same: the order website of a dairy brand like Amul (sample data, for practice) – today we start the first web server on its EC2. Begin with the isolated local lab below, then use the lesson that matches your operating system.

In this chapter

  • What a web server does
  • HTTP status codes
  • Nginx vs Apache
  • Package, service, paths per OS
  • Install on AL2023, Ubuntu, CentOS
  • firewalld and SELinux basics
  • Reading the config files
  • Everyday management commands

Concepts in this chapter

  1. 6.1What is a web server?
  2. 6.2Nginx vs Apache
  3. 6.3Quick reference: package, service, paths per OS
  4. 6.4Amazon Linux 2023
  5. 6.5Ubuntu 22.04 / 24.04
  6. 6.6CentOS Stream 9
  7. 6.7Understanding the configuration files
  8. 6.8Everyday management commands

Review and practice

  1. ★Common Mistakes I See Students Make
  2. ★Interview Questions
  3. ★Practice Questions and Lab Exercises

Trace the request into a useful response

Trace the request into a useful responseRequested siteName, destination and pathWeb configurationListener, virtual host, mappingApplication operationFollow the upstream connectionVerified responseStatus, content, logs and result
Read all steps
  1. Requested site

    The client connects to the intended endpoint and supplies the requested website name and resource. Reaching an IP address does not by itself select the workshop website.

  2. Web configuration

    The web server selects the applicable site and request handling. A static file can be delivered here; an application operation needs the appropriate application handler.

  3. Application operation

    A reverse proxy makes a separate upstream connection. A working timetable does not prove that the booking application or its database is healthy.

  4. Verified response

    Compare the response with the intended operation and correlate the relevant logs. Confirm the booking result separately from the successful delivery of the home page.

Turn a folder of workshop information into a useful website

A college workshop coordinator has prepared a timetable, a room map and a registration form. Keeping those files on a laptop helps the coordinator, but it does not give every student a reliable way to request them. Students need a common address, a program that waits for requests, and a predictable response when they ask for a particular resource. A web server provides that request-handling role. It is software running on a computer; the computer itself may also be called a server, which is why the same word can sound confusing at first.

Our example is a workshop booking website. The timetable can be a stored file. A booking needs application logic: check the chosen workshop, verify available seats, record the booking and return a meaningful result. Nginx and Apache HTTP Server can deliver stored content and connect incoming requests to application software. They do not turn an arbitrary folder of Python, PHP or JavaScript source into a working application merely because the folder exists.

Think about the student's actual objective. Opening the home page is useful, but the student wants a seat confirmed. A successful home-page response proves one part of the system worked. It says nothing by itself about the booking database, the student's authorization or the confirmation message. Throughout this chapter, connect each observation to the specific claim it supports. This habit makes you a much stronger troubleshooter than memorizing a long list of restart commands.

You will first follow one request, then compare the responsibilities expressed in Nginx and Apache configuration. After that, a small loopback lab lets you observe successful responses, missing content, an access denial and hostname selection. The later distribution lessons explain installation details. Use this overview to understand the mechanism before choosing commands for a particular operating system.

Follow a request through the correct boundaries

Suppose the student requests the workshop timetable. The browser identifies a destination using the URL. Name resolution may provide an IP address, or a suitable answer may already be cached. The browser then establishes the connection required by the selected HTTP version and security arrangement. Our initial examples use HTTP over TCP to keep the sequence easy to inspect. HTTPS adds TLS, while HTTP/3 uses QUIC over UDP; do not assume that every modern web request follows an identical transport exchange.

For an HTTP/1.1 example, the request includes a method, a target path and headers. The method describes the requested action. A GET asks for a representation of a resource. The target might be the timetable path. The Host header identifies the intended website when multiple names share the same listening address. The server selects its applicable configuration, decides how to handle the path and returns a response. HTTP/2 and HTTP/3 express comparable request information with their own framing and authority fields.

A response has a status, headers and, when appropriate, a body. The status gives the protocol outcome. Headers describe matters such as content type and caching. The body may contain HTML, an image, a document or structured data. A browser uses these pieces together. A stylesheet returned with unsuitable content information, or a login page returned where an application expected JSON, can cause visible trouble even when a request receives a success status.

One page usually causes several requests. The initial HTML can refer to CSS, scripts, fonts and images. A booking action can cause another request after the page has loaded. When someone says “the website is broken,” first identify the exact request and symptom. Is the HTML missing, the image absent, the browser rejecting a certificate, or the booking submission failing? These questions turn a broad complaint into something you can reproduce and investigate. They also prevent you from confusing a browser-rendering problem with a stopped web-server process.

Separate stored content from application decisions

A static resource is content the server can deliver from an existing representation without running the booking decision logic for each request. A workshop map, a stylesheet and a downloadable timetable are typical examples. Static does not mean the content can never change. The coordinator can replace the timetable file, and later requests can receive the new bytes. It means that serving that resource does not itself require calculating a personal booking result.

A dynamic operation needs application behavior. When two students attempt to reserve the last seat, the application and its data store must enforce the booking rules. A web server can accept the HTTP request and pass it onward, but the correctness of concurrent booking is an application concern. Increasing the number of Nginx workers does not automatically fix a database transaction that permits duplicate reservations. Identify the responsibility before choosing a remedy.

An application server or application runtime handles the relevant program. A Python web application might use Gunicorn, a Java application might use Tomcat, and PHP commonly uses PHP-FPM. A Node.js application may itself listen for HTTP requests. PM2 is a process manager often used to supervise Node.js programs; it is not a replacement name for every Node.js HTTP server. These distinctions help you draw the real process and connection diagram instead of putting all software into one box labelled “backend.”

Nginx commonly passes HTTP requests through a reverse proxy or uses a protocol such as FastCGI for a suitable application integration. Apache supports several integration approaches through its modules. In either case, identify both ends: which process receives the front request, which process runs the application and which protocol connects them. A PHP file accidentally delivered as text is not a successful PHP deployment. A static page showing a booking button is not evidence that clicking it will save a booking.

For our workshop site, write three rows in a notebook: timetable file, booking endpoint and booking records. Assign delivery of the file to the web layer, processing of the endpoint to the application, and persistence of the records to the database. Then add the connections between them. This simple responsibility map becomes your guide when a later exercise introduces multiple EC2 instances or a load balancer.

Distinguish the listener, the website name and the path

An IP address and port identify a transport endpoint in the examples used here. A listening process asks the operating system to accept traffic at an address and port. A hostname identifies the site the client intended to reach. A URL path identifies a resource within that site. These are related decisions, but changing one does not automatically change the others. Adding a DNS record does not start Nginx. Adding a server name does not create a DNS record. Creating a directory does not make it the active document root.

Imagine the workshop and library websites share one machine. Both names can resolve to the same address. Their requests can arrive on the same web port, while the name carried in each request selects a different configuration. This is name-based virtual hosting. Each site can have its own content root, logs and rules. A hostname is therefore essential test input, not decoration you can omit whenever an IP address is available.

For Nginx, begin by identifying the listening address and port, then the matching server name. For the simple Apache arrangement, identify the applicable address-and-port virtual hosts, then the requested name. Both products have default handling when a name does not match. Opening the bare IP can therefore show a welcome page or another site's default page even while the named workshop site is configured correctly. The result is evidence about the request you sent, not proof that the workshop configuration disappeared.

Our lab uses the reserved name workshop.test in a Host header and connects directly to loopback. It does not require buying a domain or modifying public DNS. Loopback means the computer addresses itself. A listener bound specifically to the IPv4 loopback address is different from one bound to every available interface. Use the intended binding explicitly, because the same program can be private to the local machine or reachable over a network depending on its listener and other controls.

HTTPS adds a further name-sensitive step: the TLS client commonly sends Server Name Indication so the server can select an appropriate certificate before the HTTP request arrives. Changing only the Host header of an HTTPS request is not a complete test of certificate selection. For HTTPS diagnosis, use a tool arrangement that preserves the intended URL hostname, certificate verification and destination mapping together.

Read an Nginx configuration as a request-handling map

Nginx configuration uses directives and nested contexts. A directive states a setting or instruction. Context determines where the directive applies. The main configuration can include other files, so the effective configuration may be spread across several paths. A file you edited matters only if the running service actually loads it. Begin with the active main configuration and its include statements rather than assuming that a familiar filename is automatically active on every distribution.

For a basic HTTP site, a server block groups a listening arrangement and site behavior. A location block handles matching request paths within that server. The root setting supplies a filesystem basis for ordinary static-file mapping. An index setting identifies a default resource for a directory request. These settings describe different parts of the request. Treating them as interchangeable often produces a site that works at one URL and fails at another.

Consider a root directory ending in a folder called workshop-public. For an ordinary static mapping, a request for a timetable file corresponds to the requested path under that root. Predict the complete filesystem path before testing. If you accidentally put the file one directory deeper, the server is not obliged to search all subdirectories for it. The configured mapping determines the expected location. This prediction turns a vague 404 into a precise comparison between the requested path and the deployed file.

Nginx location matching supports exact matches, prefixes and regular expressions, with defined selection rules. A short teaching configuration can be easy to follow because it uses a few simple locations. A production configuration may also contain rewrites, internal redirects and inherited settings. Do not claim that the first visually listed location always wins. When behavior surprises you, inspect the complete loaded configuration and the request that triggered it.

The command-line configuration test checks syntax and attempts to open referenced files. It is an essential preflight, but it cannot prove that a booking operation works or that a public client can reach the machine. A configuration can be syntactically valid while referring to the wrong content directory or an unavailable upstream. Follow the test with a request that checks the intended name, path, response and content. See the Nginx command-line reference and HTTP core directive reference when checking exact directive behavior.

Trace the second connection made by a reverse proxy

A reverse proxy accepts a client request and communicates with another server on the client's behalf. For the workshop application, Nginx may receive the browser request and open a separate connection to an application listening on a local port. The browser-to-Nginx connection and the Nginx-to-application connection have separate addresses, ports, timeouts and possible failures. One working connection does not guarantee the other works.

Suppose the timetable loads but booking requests return a gateway error. If the timetable is served locally while booking requests are proxied, that pattern is useful evidence. You already know the front listener and at least one file path work for your test. Next inspect the application destination and relevant logs. Restarting the whole machine immediately would discard useful evidence and introduce disruption without identifying the failed boundary.

The upstream URL and path handling deserve careful attention. In Nginx, the presence or absence of a URI component in a simple proxy_pass arrangement can change the path forwarded upstream. A trailing slash is therefore not always a cosmetic choice. Write down the browser path, the matching location and the path the application expects. Then test that specific mapping. Avoid copying a proxy snippet from an unrelated application without checking its route structure.

Request headers also have meaning. An application may need the original host or information about the client-facing scheme. A proxy can supply forwarding headers, but an application should trust those values only from the intended proxy path. A client can send header text too. Merely naming a header “real IP” does not make every value trustworthy. For a classroom deployment, document the trusted proxy boundary before using forwarded data for access decisions, redirects or audit records.

Do not make the application port publicly reachable just because the proxy cannot connect. First verify the intended internal listener and connection path. A local application may correctly bind to loopback, or a separate application instance may require a narrowly scoped network rule. The arrangement depends on the topology. Our introductory lab concentrates on local static handling; later labs should add an upstream as a second, explicit step rather than silently mixing several new failure points. The Nginx proxy module documentation defines the precise forwarding and timeout controls.

Express the same responsibilities in Apache

Apache HTTP Server uses its own directive names and configuration sections. A VirtualHost section groups settings for a site on an address-and-port combination. ServerName identifies the site's intended name. DocumentRoot identifies the usual filesystem basis for its content. A Directory section applies configuration to a filesystem location. These ideas overlap with the responsibilities we discussed for Nginx, but the files and syntax are not interchangeable.

One especially useful distinction is that configuring a virtual host does not by itself create a listener. The server's Listen arrangement must also accept the intended address and port. Another is that pointing DocumentRoot at a folder does not automatically satisfy every access rule. Filesystem permissions, Apache authorization settings and operating-system controls can all affect access. When a page is forbidden, identify which control refused it rather than making every file writable.

Read a small Apache example in three passes. First locate the listener and site identity. Next locate the content mapping. Finally locate access rules and logs. The three passes make the configuration easier to explain to another student. You can then predict a request for the timetable and identify the log that should record it. This is more useful than remembering that one product uses angle-bracket sections while another uses braces.

Apache can support per-directory configuration through .htaccess when the main configuration permits appropriate overrides. This is a feature with operational and performance implications, not a requirement for every Apache website. Nginx does not read an Apache .htaccess file as its configuration. Moving application files between servers without translating the relevant behavior can leave redirects or access restrictions inactive. Always verify what the destination server actually understands.

The best choice between Apache and Nginx depends on application integration, packaging, existing configuration, team experience and measured workload. Avoid a blanket rule that one is always faster or that Apache can handle only one request at a time. Apache has different processing modules, and both products support substantial production workloads. Start with a correct, maintainable setup, then measure the bottleneck in your own scenario. The Apache getting-started guide, virtual-host guide and configuration-section reference provide the underlying rules.

Identify the operating system before using an installation command

The software's name, package name, service name and configuration path do not always match. Ubuntu commonly packages Apache as apache2, while Amazon Linux 2023 and CentOS Stream commonly use httpd. Nginx commonly retains the nginx name. The operating-system release and package source determine the actual files and service integration. A missing path can therefore mean you followed instructions for a different package layout, not that installation failed.

On Ubuntu, Apache configuration commonly lives under its apache2 directory, with tools and directories for enabling sites and modules. Ubuntu's Nginx package commonly includes sites-available and sites-enabled. Other Nginx packages commonly use included files under conf.d. These are packaging conventions. The include directives in the active configuration remain the decisive evidence. A symbolic link in a directory the service never includes has no magical effect.

Amazon Linux 2023 uses DNF for package management. Its release-version repository model also matters when planning updates. Ubuntu uses APT for the usual distribution packages. Refreshing package information is different from upgrading installed programs. Installing a package may start a service automatically on some systems, so first check whether another process already owns the desired port. Installing both web servers and expecting both default services to bind the same address and port usually creates a conflict.

Prepare a small inventory before an installation exercise: distribution and release, package source, selected web server, current port owner, intended configuration file and rollback plan. This information prevents a student from copying a command into the wrong host. In a dedicated lab, choose one web server first. Learn the second with a separate instance, an alternate loopback port or a separately controlled configuration. The Ubuntu Apache installation guide, Ubuntu Nginx installation guide and Amazon Linux package-management guide are the appropriate starting points for those environments.

Apply a change with a clear before-and-after check

A useful configuration change begins with a prediction. Suppose the workshop timetable must move from one content directory to another. Record the currently expected response, the file you will change, the new path and a way to return to the previous configuration. A backup is useful when it contains the actual active files and can be restored. A copy of an unrelated example configuration does not provide a rollback for your running service.

Use the sequence inspect, edit, test, apply and verify. Inspect the active configuration and the current request result. Edit only the intended configuration. Test it with the server's configuration checker. Apply it using the service's supported reload or restart behavior. Then make a fresh request for the actual hostname and path, check the expected content and inspect the relevant logs. Each step answers a different question, so skipping one leaves an uncertainty behind.

A reload generally asks the service to adopt configuration while handling its process lifecycle in the supported way. For Nginx, a successful reload starts workers with the new configuration and retires old workers gracefully. A restart stops and starts the service and may interrupt work. Some changes need a restart, and some services have different reload semantics. Do not teach “always restart” or “reload can never interrupt anything” as universal rules. Use the installed service definition and product documentation.

Do not apply a candidate that failed its configuration test. The current service may still be serving with its previous in-memory configuration, which gives you time to correct the file. A stopped service followed by a failed start is a different, less comfortable situation. Our lab deliberately tests an invalid candidate without applying it, so you can observe this difference. The Nginx beginner guide and Apache lifecycle documentation explain their respective control behavior.

Read status codes and logs as evidence

A status code describes a response, not a complete diagnosis. A 403 means the request was understood but refused under the applicable handling. Possible causes include an explicit access rule, filesystem access or a directory request for which listing is not allowed. A 404 means the requested resource was not found under the responding component's mapping, or that the component chose not to disclose it. A wrong site selection can therefore produce a 404 even though the desired file exists in another site's directory.

A 502 from a gateway or proxy points toward an invalid upstream response or a failure while obtaining one. A refused connection to an application is one possible situation. A 504 means the gateway did not receive a timely response from an upstream needed to complete the request. Neither code tells you to increase every timeout immediately. First establish which component generated the response, which upstream it used, and whether that application was reachable and doing useful work.

The access log records handled requests according to the configured format. The error log records server events and problems at the configured logging level. Correlate the timestamp, path, response status and relevant request identifiers when available. A log entry for yesterday's timetable request does not explain today's booking failure. Likewise, the absence of an entry in one file may mean you inspected the wrong virtual host log, the request never reached that component or logging is configured differently.

Imagine the coordinator reports that the site worked locally but not from a student's laptop. Record the local URL used. If the local test reached a loopback listener, an external client is not using the same path. If the external request never appears in the intended access log, investigate the destination, listener and intervening network controls before editing the timetable file. If it appears with the wrong hostname, fix the test or site selection. If it appears as a booking-path gateway error, move toward the application connection.

Use a short observation record: time, source computer, requested URL, destination, response status, a small relevant body sample and the matching log evidence. Keep credentials and personal data out of classroom examples. This record lets another student reproduce the issue and separates observed facts from guesses. The Apache logging guide and Nginx access-log reference explain the configurable log formats.

Keep transport protection, network access and file access distinct

HTTPS protects the connection using TLS and allows the client to validate the server identity through its certificate arrangement. It does not automatically secure the application code, authorize a booking or repair unsafe file permissions. A valid certificate for the wrong hostname still fails the intended identity check. A redirect from HTTP to HTTPS is useful only when the HTTPS endpoint actually works. Treat certificate issuance, installation, renewal and verification as an ongoing operating responsibility.

Network controls decide which traffic can reach which endpoint. An AWS security group is associated with network interfaces and evaluates permitted traffic; it does not launch a web process or grant a Linux account permission to read a file. A host firewall is another control inside the operating system. The application may then apply its own login and authorization rules. These layers work together, but success at one does not replace the others.

Filesystem permissions determine whether the serving process can traverse the parent directories and read the intended content. The permissions of the final HTML file are only part of that path. On systems using SELinux, policy and labels can impose additional access controls. Diagnose a denial using the relevant evidence and distribution guidance. Making everything world-writable or disabling SELinux broadly removes useful controls without teaching you which access was actually missing.

Public content should be separated from private application configuration, credentials, backups and uploads requiring authorization. A folder called backup is not private merely because it is not linked from the home page. If it lies under a publicly served mapping, a request may still reach it. For the workshop site, the public timetable and room map belong in the public content area; student records and database credentials do not. Review what a path exposes before choosing it as a document root.

For this introductory lab, loopback binding keeps the exercise local. It is not a complete security design for a production website. A production design needs the intended public entry point, administrative access, TLS boundary, application permissions and monitoring to agree. Consult the Nginx HTTPS guide and your distribution's SELinux documentation for the mechanisms involved.

Lab: observe a separate local Nginx website

Use a Linux learning environment where Nginx and curl are already installed and you may run your own local process. This lab does not require changing the system service. It uses a fresh directory, a separate configuration and PID file, and a loopback listener on a high port. Keep the same terminal open so its directory variable remains available. If the selected port is occupied, choose another unused high port consistently; do not stop an unrelated process to free it.

First create a directory reserved for this attempt and a tiny timetable. Print the directory so you know exactly where the exercise lives. The text file makes the expected response easy to inspect. We use a separate filename for the Nginx configuration so that every control command can explicitly select it.

web_lab=$(mktemp -d /tmp/workshop-web.XXXXXX)
mkdir "$web_lab/www"
printf 'Workshop schedule: robotics at 10:00\n' > "$web_lab/www/index.txt"
printf 'Lab directory: %s\n' "$web_lab"

The following configuration is complete for this small exercise. The first site is a default response for unmatched names. The second is our workshop site. Both listen only on loopback. Each temporary-storage path belongs to this lab, so the process does not need to write to the package's global temporary directories. The explicit staff-path denial gives us a controlled 403 to compare with a missing file.

cat > "$web_lab/nginx.conf" <<EOF
worker_processes 1;
pid $web_lab/nginx.pid;
error_log $web_lab/error.log notice;
events { worker_connections 32; }
http {
  access_log $web_lab/access.log combined;
  client_body_temp_path $web_lab/body;
  proxy_temp_path $web_lab/proxy;
  fastcgi_temp_path $web_lab/fastcgi;
  uwsgi_temp_path $web_lab/uwsgi;
  scgi_temp_path $web_lab/scgi;
  default_type text/plain;
  server {
    listen 127.0.0.1:18886 default_server;
    server_name _;
    return 404 "Unknown practice host\n";
  }
  server {
    listen 127.0.0.1:18886;
    server_name workshop.test;
    root $web_lab/www;
    index index.txt;
    location = /staff { deny all; }
  }
}
EOF
nginx -p "$web_lab/" -c "$web_lab/nginx.conf" -t

Read the test output before continuing. A successful test means the candidate passed that check; it is not yet a running listener. If the test reports a missing executable, unsupported directive or path permission problem, resolve that specific issue in the learning environment. Do not add sudo merely to make an unexplained failure disappear. This process is intended to run under your ordinary account with files it owns.

Start the dedicated instance, then request the same path with two different Host values. The connection destination remains identical. Only the requested website name changes. This is the simplest way to see that reaching a machine and selecting the intended website are separate decisions.

nginx -p "$web_lab/" -c "$web_lab/nginx.conf"
curl --noproxy '*' --max-time 5 -i -H 'Host: workshop.test' http://127.0.0.1:18886/
curl --noproxy '*' --max-time 5 -i -H 'Host: unmatched.test' http://127.0.0.1:18886/
curl --noproxy '*' --max-time 5 -i -H 'Host: workshop.test' http://127.0.0.1:18886/missing.txt
curl --noproxy '*' --max-time 5 -i -H 'Host: workshop.test' http://127.0.0.1:18886/staff

Expect the workshop root request to return 200 and the timetable text. The unmatched name returns our deliberate default 404 message. The missing file returns 404 from the selected workshop site. The staff path returns 403 because of our explicit rule. Notice that the two 404 responses have different explanations. Status alone would not tell you which one occurred; the request name, response content and configuration complete the reasoning.

Now change only the timetable file and request it again. This demonstrates a content change without a configuration reload. In a larger system, caches can affect when a change appears, but our direct local exercise has no additional caching layer configured. Keep that limited conclusion in your notes rather than assuming every public website updates immediately under every deployment arrangement.

printf 'Workshop schedule: robotics at 11:00\n' > "$web_lab/www/index.txt"
curl --noproxy '*' --max-time 5 -i -H 'Host: workshop.test' http://127.0.0.1:18886/
tail -n 8 "$web_lab/access.log"

Finally stop only this lab's Nginx instance by selecting the same prefix and configuration. Read the process-specific log and confirm the lab PID file has gone before removing anything. You can keep the directory as evidence of your exercise. If you later remove it, inspect its exact printed path and contents first; do not replace the variable with a broad system path.

nginx -p "$web_lab/" -c "$web_lab/nginx.conf" -s quit
test ! -e "$web_lab/nginx.pid"
printf 'PID-file absence check status: %s\n' "$?"

A graceful shutdown may take a moment, so a nonzero absence check immediately after signalling is a reason to observe again, not to kill every Nginx process. Your completion evidence is the expected response sequence, relevant access-log entries, the changed timetable and the dedicated process stopping. No public DNS or security-group change is needed for this loopback exercise.

Lab: distinguish a rejected candidate from a running configuration

Repeat the local setup in a fresh directory. Before changing the configuration, save a copy of that lab's valid file. Add one clearly invalid teaching directive to the candidate and run its configuration test. The test should fail. Do not issue a reload. Instead, make a fresh request to the already running lab website. It should still use its previously loaded valid configuration. Record both results: invalid candidate on disk, valid active service in memory.

Restore the valid candidate from your lab copy, run the test again and apply a reload using the same explicit prefix and configuration. Then verify the timetable request and inspect the error log for the reload event. The point of this experiment is not to memorize the exact wording of an error message. It is to observe that editing, testing and applying are separate operations. A file saved in an editor does not automatically become the running configuration.

For an Apache learning environment, make a paper version of the same experiment first: identify the active configuration, its configtest command, the supported graceful reload action and the request you would use afterward. Distribution wrappers can supply required environment settings, so use that package's documented control command. Do not run a generic Apache control command on a shared machine merely because it appeared in a tutorial. The change should belong to the lab instance you can identify and restore.

Practice tasks with an expected reasoning result

  1. Map two site names. Draw the workshop and library names sharing one listener. Give each a separate content root and log. Explain what an unmatched name receives and which test proves the workshop site was selected. Your answer should include the requested name, not just the server address.
  2. Investigate a missing timetable. The service is running and the response is 404. Write the complete requested path and predicted filesystem path. Check the selected site before changing permissions. Explain why restarting the service is not your first diagnostic step.
  3. Investigate a booking failure. Static content works but a booking request returns 502. Draw the front connection and the upstream connection separately. List the listener, destination and logs you would inspect on each side. Do not assume the database is responsible until the evidence leads there.
  4. Plan a distribution migration. Move a paper design from Ubuntu Apache to Amazon Linux Apache. Identify package and service names, main configuration, included site files, authorization rules and logs. Preserve the required behavior while adapting the packaging conventions.
  5. Review a proposed permission fix. A classmate suggests making the whole website directory writable by everybody after a 403. Explain which identities and parent-directory permissions you would inspect, and where SELinux evidence could matter. State the narrow access the serving process actually needs.
  6. Write a rollback record. Describe the exact configuration backup, the failed request that would trigger rollback, the restore action and the verification request. Include any application dependency affected by the change so that returning one file is not mistaken for complete recovery.

Interview questions with explained answers

How would you explain a web server to a non-IT student?

It is a program that waits for web requests and sends appropriate responses. In our example, it delivers the workshop timetable and can pass booking requests to an application. The machine supplies computing resources; the web-server program handles the protocol-facing job. I would then distinguish stored content from application decisions, because serving a form does not mean a booking has been recorded.

A default page appears when you open the IP address. Has the named site failed?

Not necessarily. The request may have selected the default virtual host because its requested name did not match the workshop site. I would test the intended hostname while controlling the destination, then inspect the relevant site configuration and log. The initial result proves that some web component answered; it does not prove which named site's configuration should have handled a different request.

Does a successful configuration test prove a deployment is correct?

No. It checks the candidate according to the product's validation behavior, including syntax and some referenced resources. A valid configuration can still select the wrong directory, point to an unavailable application or produce an incorrect business result. I would apply the validated change, make a fresh request for the intended site and operation, and compare the response and logs with the predicted outcome.

What would you inspect for a 403 response?

I would identify the responding site and requested resource, then inspect applicable authorization rules, directory traversal and file-read permissions, and relevant operating-system policy evidence. I would also check whether a directory request lacks an allowed index or listing. I would not assume that the only cause is the final file's mode, and I would avoid broad permission changes without understanding the denied operation.

How does a reverse proxy change your troubleshooting diagram?

It adds a separate upstream connection. The front listener can respond successfully while the proxy cannot obtain a useful application response. I would record the client request, the selected upstream, the forwarded path and the relevant timeout or error. This separates network reachability, protocol handling and application behavior, which may have different owners and different fixes.

When would you choose Apache instead of Nginx?

I would compare the application's integration requirements, existing configuration, supported modules, operational experience and measured behavior. For example, a supported application deployment may already rely on Apache-specific configuration. I would assess that requirement rather than claim that either product is universally superior. The practical objective is a correct, maintainable service whose performance is demonstrated under the relevant workload.

Check your understanding before moving to installation

1. A DNS record now points to an EC2 address. Does that create a web listener?

No. Name resolution and a running listener are different mechanisms. The intended process must be installed, configured and running, and the relevant path must permit the connection. Verify each condition with appropriate evidence.

2. The timetable changed on disk. Must every such change require a reload?

No. In our direct static-file lab, a new request reads the changed content without a configuration reload. Caching, deployment mechanisms and application behavior can change the wider situation, so test the actual path rather than turning this observation into a universal claim.

3. Two requests return 404. Must they have the same cause?

No. Our lab gives one 404 for an unmatched hostname and another for a missing file under the correct site. Compare the full request and relevant configuration. The status narrows the outcome but does not uniquely identify the cause.

4. A web-server process can read the file. Does this prove that every HTTP request may access it?

No. Web-server authorization, path mapping and other controls still apply. Operating-system readability is one condition, not the entire access decision. The staff-path exercise demonstrates an explicit denial despite using a controlled local environment.

5. A successful home page proves that bookings are saved. Agree?

Disagree. The home page may be a static resource while booking requires an application and database operation. Verify the booking result and its persistence separately. A meaningful test follows the user's intended outcome, not only the first visible page.

Revision cards for the complete request path

Listener
The process endpoint accepting traffic on an address and port. Confirm the actual binding and owner before diagnosing a distant client's failure.
Virtual host
The site's configuration selected within an applicable listening arrangement. The requested name and default handling matter when several sites share a machine.
Document mapping
The relationship between a requested resource and its content or application handler. Predict the selected path before changing files or access rules.
Reverse proxy
A component that accepts the front request and communicates with an upstream. Treat those connections as separate parts of the evidence trail.
Configuration lifecycle
A candidate is edited on disk, tested, applied and then verified. Keeping those stages distinct makes a failed test easier to recover from.
Useful verification
Check the intended hostname, request path, response meaning, related logs and user outcome. A running process or a success status alone is a narrower observation.

Before opening the operating-system-specific lesson, explain the workshop request path aloud without looking at the commands. Then choose one failed observation from the lab and describe the next check it justifies. If you can connect an observation to a precise next step, you are ready to install and manage the software with understanding rather than simply repeating terminal lines.

Primary references

Before you start: where web servers fit

A website request can pass through a CDN, a load balancer and a web server before reaching an application. Nginx and Apache can serve files and forward requests to application software such as PHP-FPM, Gunicorn, a Node.js HTTP application, Tomcat or Kestrel. PM2 is a process manager often used to supervise Node.js applications. The exact request path depends on the site architecture.

In this chapter you will install nginx and Apache on Amazon Linux 2023, Ubuntu and CentOS Stream 9, learn where their files live, and practise the safe daily routine: test, reload, read the logs. Every later chapter (static hosting, dynamic sites, WordPress, load balancing) builds on this one, so go slowly and type each command yourself.

Request pathBrowsernginx / ApacheApp server(FPM, Gunicorn, Node.js,Tomcat, Kestrel)Database
The web server follows its request-handling configuration: it can serve files, send redirects or errors, and forward selected requests to an application.

Architecture example. A site can place a CDN and load balancer in front of several web servers. A small lab can start with one Nginx instance, but that single process does not provide a distributed CDN or remove the machine as a failure point. Add components when the required delivery and availability behavior calls for them.

Real examples you will relate to

Workshop example: A timetable can be served as a file, while a booking request needs application logic and a database result. Draw those responsibilities separately. A receptionist analogy can help introduce forwarding, but actual web handling follows protocols, configuration and access rules.

After this part you will be able to

  1. Install and start nginx or Apache on three Linux distributions.
  2. Find the config, web root and log paths quickly.
  3. Test, reload and verify changes safely.
  4. Explain 403, 404, 502 and 504 with one cause each.

Key terms

  • Web server: Serves files and proxies apps: nginx, Apache.
  • Application runtime or server: Runs application logic through an appropriate deployment such as PHP-FPM, Gunicorn, a Node.js application, Tomcat or Kestrel.
  • Reverse proxy: Receives requests and forwards them to an app.
  • Status 403: Forbidden: permissions, SELinux or no index file.
  • Status 502: A gateway could not obtain a valid upstream response; inspect the upstream connection and response evidence.
  • SELinux: Mandatory access control on RHEL-family systems.

Mini case study

Suppose we are a junior cloud engineer at a Bengaluru e-commerce startup (sample data). The team runs a PHP admin, a Node.js storefront API and a Python report job on two EC2 instances. Using this chapter, you write a one-page runbook: which service listens where, how to test and reload each one, which logs to read, and which ports are public (only 80 and 443, plus 22 from the office IP). New team members can then fix most problems on their own.

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 scenario

Mumbai Dabba Express is a food delivery business in Mumbai. Tukaram Gaikwad 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

Config changes only apply after the service restarts or reloads.

Restart the nginx service.

  1. Find the Linux command that does this job.
  2. Add the options (like -r or -h) the task needs.
  3. Add the file names, folders or users in the right order.
  4. 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.

  1. Find the Linux command that does this job.
  2. Add the options (like -r or -h) the task needs.
  3. Add the file names, folders or users in the right order.
  4. 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.

  1. Find the Linux command that does this job.
  2. Add the options (like -r or -h) the task needs.
  3. Add the file names, folders or users in the right order.
  4. 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.

  1. Find the Linux command that does this job.
  2. Add the options (like -r or -h) the task needs.
  3. Add the file names, folders or users in the right order.
  4. 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.

  1. Find the Linux command that does this job.
  2. Add the options (like -r or -h) the task needs.
  3. Add the file names, folders or users in the right order.
  4. Use sudo if the job changes system files or users. Click Check answer.

Easy Download code from GitHub

git clone obtains a working checkout. Review the project instructions, dependencies and build output before deploying it.

Clone https://github.com/mumbaidabba/website.git into the current folder.

  1. Find the Linux command that does this job.
  2. Add the options (like -r or -h) the task needs.
  3. Add the file names, folders or users in the right order.
  4. Use sudo if the job changes system files or users. Click Check answer.

Medium Test the nginx config

A test catches typos before a restart takes your site down.

Check the nginx configuration files for errors.

  1. Find the Linux command that does this job.
  2. Add the options (like -r or -h) the task needs.
  3. Add the file names, folders or users in the right order.
  4. 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.

  1. Find the Linux command that does this job.
  2. Add the options (like -r or -h) the task needs.
  3. Add the file names, folders or users in the right order.
  4. 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 rule. An HTTPS-only site uses a different listener, and reachability also requires the intended routes and running service.

Allow inbound TCP port 80 from 0.0.0.0/0 on security group sg-01a03134416a4c3b2.

  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. Flags can be in any order. Click Check answer.

Medium CloudFormation: web security group

This exercise describes an HTTPS listener rule. Network rules, TLS configuration and application access controls have separate responsibilities.

Template with an AWS::EC2::SecurityGroup that allows TCP 443 from 0.0.0.0/0. Add a GroupDescription.

  1. Start from the top-level keys the task names.
  2. Indent child keys with 2 spaces (no tabs).
  3. Fill in each property with the value from the task.
  4. 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 mumbaidabba-web-sg with description "Web servers" in vpc-00313441cadeadbee.

  1. Read the task and decide which AWS service it is about.
  2. Write aws, then the service name, then the operation (the action word).
  3. Add each needed flag (--name) followed by its value from the task.
  4. 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/mumbaidabba inside /etc/nginx/sites-enabled/.

  1. Find the Linux command that does this job.
  2. Add the options (like -r or -h) the task needs.
  3. Add the file names, folders or users in the right order.
  4. Use sudo if the job changes system files or users. Click Check answer.