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

Chapter 10: Dynamic Website Hosting (PHP, Python, Node.js with MySQL)

AWS Cloud

10.6 Reverse proxy to the Python/Node app

Students in my class ask, “Sir, my app runs on port 3000, so why not open 3000 in the security group?” In this one-host design the assigned front listener handles the site routing, logs and configured TLS. The app listens only on loopback and still needs the right checks on every route the front exposes.

Nginx reverse proxy

Check the Nginx instance’s effective configuration and its enabled site includes. Add only the assigned virtual host or location. The private Nginx exercise can be completed without editing a shared service.

Use the app’s actual assigned port. Test the intended hostname, public path and upstream path, then verify any redirect or asset requested by the browser.

Validate the effective config using the instance’s own executable and flags. Follow its approved activation and rollback procedure. Where SELinux is enforcing, confirm a denial through the approved operator workflow before choosing a scoped policy change.

Apache reverse proxy

Use a matching local prefix and destination in ProxyPass, and handle suitable redirect headers with ProxyPassReverse. The private Apache example keeps its host and proxy choice local to the exercise.

  • AL2023 / CentOS: inspect the installed HTTP Server's active include directories and loaded modules. Verify any SELinux denial separately under the approved host process.
  • Ubuntu: inspect the active site and module configuration. Enable only the assigned site through your lab procedure and verify existing shared sites still route as expected.

Ravindra Bagale's Tip

For a 502 Bad Gateway, send a direct GET to the exact upstream path, address and port used by the front. Compare the front error evidence with the app’s listener and service logs. Check protocol and runtime isolation if they disagree.

Lab

In the loopback exercise, record a healthy front route and upstream read. Stop only the owned fixture, compare the failed direct connection with the front’s 502 and confirm the front’s own marker still works. Restart the fixture and verify the report again.

Give learners one stable website address for a private app

The training club has a website with a public course description. A separate Node or Flask application reads a study report. On the assigned host, the app answers requests at its own loopback port. A classmate cannot reach that loopback address from their laptop because their laptop's loopback address means the laptop itself. The goal is to give them one named site and a report link. The front web server receives their request for that link and makes another request to the application on the same host. The app can keep its private listener while the proxy presents the public route.

A reverse proxy is a server acting on behalf of one or more backend services. From the reader's perspective, it is the address they contact. From the application's perspective, it is the peer making the particular upstream HTTP connection. Upstream means the destination the proxy connects to after selecting a route. A forward proxy is arranged to make requests on behalf of its clients. Here the course owner runs the proxy as part of the course service and selects the application that should receive each agreed path.

Two connections are involved. The browser could make an HTTPS connection to the front server on port 443. The front server could make an HTTP connection to the app on a private port on the same machine. The certificate and hostname used on the browser connection must match the deployed site. The security requirements for the second connection depend on how and where the two services operate. If they later move to different hosts or require authenticated transport locally, choose an appropriate private network and transport plan for that connection too. Avoid describing the whole path as encrypted based only on what the browser shows.

The examples use a public prefix of /training/ and an upstream app whose routes start at the root. The front can still serve a separate page such as /site-check while it gives report requests to the app. A reader types the same site name in either case. The path selection is the mapping you configure. That mapping lets the two applications evolve independently, provided their URL contract and deployment details are tested together.

  1. The browser connects to the public name and requests /training/api/students.
  2. The front server selects the virtual host for that name and the rule for the /training/ path.
  3. The selected rule opens an upstream request and hands the app /api/students.
  4. The app handles that path and returns a status, headers and a response body.
  5. The front logs its result and passes an appropriate response back over the original browser connection.

The localhost example isolates pure routing. The sample application returns two fixed synthetic rows to show that a route reached application code. This exercise uses no credentials or database. Once the boundaries are clear, test the real application through the same path. The Flask and Express lessons have separate readiness and data routes for checking their storage dependency. Keep those distinctions when deciding which endpoints are safe and useful for a public site.

Decide which addresses and ports are supposed to accept traffic

Plan listeners before opening any rules. A listener is a running process waiting for network connections at an address and port. A public listener might be on an interface associated with an accessible host, while a loopback listener only works through the loopback interface of its networking environment. A security group rule can authorize certain network traffic at an EC2 instance's interface. It cannot make a process bound only to loopback start listening at the private or public interface. Conversely, binding an application widely still calls for sufficient network, host and application access controls.

The web front usually accepts selected incoming HTTP or HTTPS traffic. A training deployment with a load balancer can allow the front instance only from that load balancer's security group on its intended target port. Another topology sends browser traffic to an assigned public reverse proxy. In that case the correct source and routing plan can be different. The one-machine practice lab keeps both listeners private. It runs without AWS resources, external browser traffic or changes to a security group. If the front runs in a separate container, its loopback reaches the network namespace for that container. Use the intended container network and service address when the app's listener is in a different namespace.

ConnectionPractice destinationTeaching evidence
Client to Nginx127.0.0.1:18960At least one request returns the Nginx-only marker.
Client to optional Apache front127.0.0.1:18962The correct private virtual host and mapping return the report.
Either front to the app127.0.0.1:18961The real received request path appears in the app's JSON.
Browser to the report in a managed deploymentThe approved public name and front listenerDNS, TLS, virtual host and the expected course report all agree.

Separate the question of reaching a port from the question of permission to see data. A process that answers via a reverse proxy is still receiving externally initiated requests for the exposed route. That route needs the same appropriate validation and application access decisions as any externally reachable endpoint. Moving the app onto loopback keeps direct external clients from connecting to that listener and gives you a place to control front routing. Review which APIs, management paths and error details the proxy makes available. An application check that should remain internal deserves an explicit deployment decision.

A virtual host is the set of handling settings for a particular site served by the web server. Several named sites can share the same address and port while having different document roots or app targets. The front uses request information, including the hostname, to choose. A request to the bare IP may select a default site, which could be healthy but entirely different from the club report. In HTTPS, host selection starts during the TLS setup with the requested server name. Then the HTTP request provides its own authority. A named end-to-end test should use the actual expected name and certificate validation.

Choose a public path contract and work out the upstream path

The guide uses a public path of /training/api/students. The report code already handles /api/students. There are two sensible designs. The front can translate the prefix before forwarding, and the app can keep its root-relative server routes. Alternatively, the front can keep the full path, and the app can register its own prefixed routes. Draw two columns with the path the reader enters and the path the application actually receives. Add the route the app must match and the path any redirect, stylesheet or fetch call asks the reader to open next. A mapping is usable only when the follow-up requests go where you intended.

Example Nginx ruleUpstream for /training/api/students?city=PuneRequirement
location /training/ and proxy_pass http://127.0.0.1:18961/;/api/students?city=PuneThe app serves root-based routes.
location /training/ and proxy_pass http://127.0.0.1:18961;/training/api/students?city=Pune in this simple mappingThe app serves the prefixed routes.
location /training/ and proxy_pass http://127.0.0.1:18961/reports/;/reports/api/students?city=PuneThe upstream app has a different prefix.

In the first example, the last slash of the proxy target is the URI part of the directive. For this plain prefix route, Nginx replaces the matching normalized part with the URI you supply. In the second example, the target has no URI portion. For the underlying comparison, no rewrite directives or variables are involved. More elaborate Nginx rewrites, matching styles and variables can alter these rules. Rather than remembering a slash as magic, read it as the choice between replacing a matched URI prefix and forwarding the path in the simple case.

Apache HTTP Server's comparable rule maps a local path prefix to an upstream URL. In its simple prefix examples, keep the slashes aligned at the end of the source path and destination. Apache checks the relevant rules in order. Put a more specific rule ahead when a broader rule would otherwise match the same path. Nginx's own location selection has different rules for exact, prefix and regular expression matches. For either server, test the meaningful paths when adding a broad catch-all or specific exception. Reading a single line out of its surrounding context can hide which handler actually wins.

Follow a successful response into the browser. A document from /training/ which links to api/students with no leading slash resolves relative to the document path and works in this straightforward example. A link to /api/students starts from the origin's root and leaves the mapped prefix. A generated URL or front-end router may choose differently. A redirect to the internal application address points the browser somewhere it may not reach. Proxies can rewrite certain response headers, but they do not generally rebuild the page's HTML and asset URLs for this mapping. For a real app, review URL generation, redirects, asset paths, follow-up API requests and cookie scope together.

A best first check is a precise question: if the reader opens /training/api/students?city=Pune, which path and query should the app report receiving? The practice source echoes them to make the mapping visible. Next, check a deliberately missing route to learn which component can send its own 404. Finally verify the front's static marker to establish that other known paths still use their own handlers. These few requests tell you more about the agreed site contract than repeatedly refreshing the site root.

Lab one. Run an identifiable upstream on loopback

Use a new empty workspace on a local machine or assigned disposable lab host. You need Python 3, curl and the Nginx exercise binary from your approved installation. For the alternate front, use Apache HTTP Server with the required proxy modules. Use the fixed practice ports only if they are assigned and free. If you select replacements, change the listener, proxy targets, redirect string and test URLs consistently. All processes in this example bind only to local IPv4. Each long-running command should have its own terminal so you can stop just the processes it started.

Save the following as practice_app.py. The records are deliberately fictional. The app exposes just enough routes to test HTTP path translation, a redirect, a known absence and an intentionally slow response. The direct code is a teaching fixture using Python's small HTTP server. Use a managed application server like the previous lessons when verifying a real app. No web server is expected to run Python scripts merely because a file has a Python extension. The second connection targets an already running HTTP listener.

from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import urlsplit
import json
import time

BIND = "127.0.0.1"
PORT = 18961
STUDENTS = [
    {"id": 1, "name": "Practice Student A", "city": "Pune"},
    {"id": 2, "name": "Practice Student B", "city": "Nagpur"},
]

class StudyReport(BaseHTTPRequestHandler):
    def send_payload(self, status, media, payload, headers=()):
        self.send_response(status)
        self.send_header("Content-Type", media)
        self.send_header("Cache-Control", "no-store")
        self.send_header("Content-Length", str(len(payload)))
        for key, value in headers:
            self.send_header(key, value)
        self.end_headers()
        try:
            self.wfile.write(payload)
        except (BrokenPipeError, ConnectionResetError):
            return

    def json_body(self, status, content):
        payload = json.dumps(content).encode("utf-8")
        self.send_payload(status, "application/json", payload)

    def do_GET(self):
        request = urlsplit(self.path)
        if request.path == "/":
            self.send_payload(200, "text/html; charset=utf-8",
                b'<!doctype html><html lang="en"><title>Study Report</title>'
                b'<h1>Practice report</h1><a href="api/students">See students</a></html>')
        elif request.path == "/health":
            self.json_body(200, {"status": "ready", "source": "practice-upstream"})
        elif request.path == "/api/students":
            self.json_body(200, {"path": request.path, "query": request.query,
                                  "rows": STUDENTS, "source": "practice-upstream"})
        elif request.path == "/bounce":
            target = f"http://{BIND}:{PORT}/api/students"
            self.send_payload(302, "text/plain", b"Continue to the report\n",
                              [("Location", target)])
        elif request.path == "/slow":
            time.sleep(3)
            self.json_body(200, {"status": "finished"})
        else:
            self.json_body(404, {"error": "route missing", "path": request.path,
                                 "source": "practice-upstream"})

if __name__ == "__main__":
    with ThreadingHTTPServer((BIND, PORT), StudyReport) as server:
        print(f"Practice application listening at http://{BIND}:{PORT}", flush=True)
        server.serve_forever()
python3 practice_app.py

Keep that terminal open. In a separate terminal run the direct check. The no-proxy flag keeps this expected local request on your own machine even if the shell sets an HTTP proxy. The maximum time prevents the client from waiting indefinitely. Include response headers so you can record the status and media type as well as the markers.

curl --noproxy '*' --max-time 5 --include \
  'http://127.0.0.1:18961/api/students?city=Pune'

Expect 200, application/json, path /api/students, query city=Pune, source practice-upstream and two synthetic records. The fixture reports the query to show that it arrived at the right component. It intentionally performs no filtering by city. If this direct check fails with a connection error, verify that the owned app terminal showed its successful start. A port-in-use error means another listener is already there or a training copy is still running. Choose an assigned free port or stop only the copy you own. Finish the direct check before configuring a front server.

Lab two. Map the prefixed route through a private Nginx instance

In the same empty study workspace make a logs directory and save the next block as nginx.conf. This is a complete little configuration for a private worker, separate from the web server for your usual machine. The error log, access log and PID file belong to this workspace. It uses no privileged listener. The variable names in the configuration are interpreted by Nginx. If writing with a shell here-document, quote its delimiter to avoid the shell expanding them before the config is saved.

worker_processes 1;
pid nginx.pid;
error_log logs/error.log info;

events { worker_connections 64; }

http {
    log_format practice '$request status=$status upstream=$upstream_status '
                        'target=$upstream_addr total=$request_time '
                        'upstream_time=$upstream_response_time';
    access_log logs/access.log practice;

    server {
        listen 127.0.0.1:18960;
        server_name localhost;

        location = /site-check {
            default_type text/plain;
            return 200 "nginx front is answering\n";
        }

        location = /training {
            return 308 /training/;
        }

        location /training/ {
            proxy_pass http://127.0.0.1:18961/;
            proxy_http_version 1.1;
            proxy_set_header Host localhost;
            proxy_set_header X-Forwarded-For $remote_addr;
            proxy_set_header X-Forwarded-Proto $scheme;
            proxy_set_header X-Forwarded-Host localhost;
            proxy_set_header X-Forwarded-Port $server_port;
            proxy_set_header X-Forwarded-Prefix "";
            proxy_set_header Forwarded "";
            proxy_connect_timeout 1s;
            proxy_read_timeout 1s;
            proxy_redirect default;
        }

        location / {
            default_type text/plain;
            return 404 "front route missing\n";
        }
    }
}
mkdir -p logs
nginx -e stderr -p "$PWD/" -c "$PWD/nginx.conf" -t
nginx -e stderr -p "$PWD/" -c "$PWD/nginx.conf" -g 'daemon off;'

Run those commands from the lab workspace as your regular user, with the actual approved executable path if it is outside your command search path. Stop if the configuration test fails. The final command stays in that terminal so a separate probe terminal can check it. The test verifies a configuration can be read and parsed and the named resources can be opened under that invocation. It cannot prove that the separately managed app is ready, that the listener will win a port conflict, or that this is the right configuration for your public site.

curl --noproxy '*' --max-time 5 --include http://127.0.0.1:18960/site-check
curl --noproxy '*' --max-time 5 --include http://127.0.0.1:18960/training
curl --noproxy '*' --max-time 5 --include http://127.0.0.1:18960/training/
curl --noproxy '*' --max-time 5 --include \
  'http://127.0.0.1:18960/training/api/students?city=Pune'
curl --noproxy '*' --max-time 5 --include http://127.0.0.1:18960/api/students
curl --noproxy '*' --max-time 5 --include http://127.0.0.1:18960/training/no-such-report
curl --noproxy '*' --max-time 5 --include http://127.0.0.1:18960/training/bounce

Expect the front check to return text with 200 without calling the app. The exact training slash redirect returns 308 and a location ending in /training/. The report returns HTML; the prefixed student request returns 200 JSON with the upstream path and query from the direct test. Without the prefix, the same student request returns a front text 404. With an unknown suffix, it returns the app's JSON 404. The last request returns a 302 from the upstream with a redirected location for the front's /training/api/students path. Inspect the destination before following it. Then request that destination from the front and capture the synthetic rows.

To see the other URI contract in action, copy the working configuration before trying a change. In the practice file only, remove the target slash after the port in the proxy directive. Validate this private configuration and restart just the private Nginx instance from its terminal. Now the upstream should report path /training/api/students on its 404. The front found the configured proxy location and the app received a request. The app no longer matched the path. Restore the working copy, test the configuration and start the same front again. Re-run a real successful report, the direct app check and the front marker. The restored evidence is the point of the rollback exercise.

Lab three. Translate the same prefix using Apache HTTP Server

The Apache example is an alternative front for the same fixture on a different private port. It assumes a lab-specific base configuration that already loads a supported MPM, the HTTP proxy modules mod_proxy and mod_proxy_http, and the header and logging modules. A standalone Unix lab base also needs its required platform modules, including mod_unixd if it is dynamic on that installation. Set its private DefaultRuntimeDir to an existing directory you own for resources such as proxy mutex files. On Debian-based layouts module activation is commonly managed by the distribution. Other packages may load modules from their own include directory. Find out how the assigned instance already does this and check its loaded modules with its configuration. Keep the listener and virtual host in the separate lab context. Do not introduce a second Listen directive for an address already owned by that config.

Listen 127.0.0.1:18962

<VirtualHost 127.0.0.1:18962>
    ServerName localhost
    ProxyRequests Off
    ProxyAddHeaders Off
    ProxyPreserveHost Off
    RequestHeader unset Forwarded
    RequestHeader unset X-Forwarded-For
    RequestHeader unset X-Forwarded-Proto
    RequestHeader unset X-Forwarded-Host
    RequestHeader unset X-Forwarded-Port
    RequestHeader unset X-Forwarded-Prefix
    ProxyPass "/training/" "http://127.0.0.1:18961/"
    ProxyPassReverse "/training/" "http://127.0.0.1:18961/"
</VirtualHost>

Use this within the approved private Apache instance. Validate its exact configuration with the executable and flags for that instance, such as httpd -t -f /absolute/lab/httpd.conf. Then start the same configuration, using its assigned private PID, runtime and log paths and a foreground command under your lab procedure. ProxyRequests Off keeps the forward proxy disabled while allowing the reverse mapping. The practice backend has no need for the incoming browser's hostname, scheme or forwarded identity. The supplied header policy drops those fields and does not automatically append proxy values in this example. If a real app needs them, engineer the legitimate source and trust settings deliberately.

curl --noproxy '*' --max-time 5 --include \
  'http://127.0.0.1:18962/training/api/students?city=Pune'
curl --noproxy '*' --max-time 5 --include http://127.0.0.1:18962/training/bounce
curl --noproxy '*' --max-time 5 --include http://127.0.0.1:18962/training/no-such-report

Expect the same JSON and upstream path as Nginx for the first request. For the second response, locate the returned redirect target. The upstream sent a Location header for its own loopback listener. The reverse mapping rewrites it to the Apache front and the prefixed path. For the third request record the application 404 and its path. Use /training/ with the slash for this Apache example. It includes no separate slash canonicalization rule equivalent to the Nginx exact rule.

The pair of proxy directives operates in two directions. The incoming rule selects the upstream URL for a public path. The reverse rule can translate suitable outbound redirect response headers. It does not generally rewrite application body URLs or set every cookie attribute necessary for deployment under a prefix. Check the site's normal browser flow, including any login redirect and assets, before treating two command-line checks as deployment acceptance. Turn back to the common mapping table if the app deliberately serves a URL prefix of its own.

If the Apache exercise sends the front's default page, check that you started the lab's exact base config, bound the correct private address and used the matching hostname. If it receives an ordinary proxy module configuration error, check the actual module list before changing a public service. After finishing, shut down only that private foreground Apache instance, leaving the underlying app and any independent Nginx lab processes running until you need to stop them. The study report remains available through a learner's selected private front.

Decide which request metadata the app actually needs

When the browser's request arrives at the front, the front can see the immediate peer's address and its own listener scheme. When it opens a different connection to the backend, the backend directly sees the front connection's information. In the single-machine lab, its TCP peer is loopback. If the app builds absolute links, marks a cookie secure, or logs the original client, it may need carefully supplied metadata. Header fields used for that purpose often include X-Forwarded-Proto, X-Forwarded-Host and X-Forwarded-For. A value's presence does not tell the app whether that value came from a trusted front or some earlier sender.

The Nginx sample for the single front sets its own canonical host and forwards only its directly observed client address and local scheme. In this lab that means the IP and scheme of a local HTTP client. The app does not rely on those fields for identity. If the real front terminates HTTPS, its observed client-facing scheme may be HTTPS while it talks HTTP upstream. An app can use approved proxy metadata to know about that external HTTPS connection. Express uses its configured trust proxy policy for selected facts. Flask can use Werkzeug's ProxyFix with counts for the intended headers. Both require knowledge of the actual trusted hops. An application should use settings consistent with how it can be reached.

Add an Application Load Balancer in front of the web server and the topology changes. Nginx's observed client can become the load balancer and its observed scheme can be the connection from that load balancer rather than the original browser. Reusing the one-front policy could discard useful information or characterize the original scheme incorrectly. The ALB documentation describes the forwarded address header modes. Check which components terminate TLS, which values each inserts or changes, and what alternate paths could reach the app. Set framework trust and network access to accept only the explicitly trusted topology. Do not blindly enable global trust or trust a hop count if traffic can reach the service through shorter paths.

A hosted report has separate authorization, so forwarding the real user address is often optional. Health and request IDs can be enough for an exercise. Avoid recording complete session headers or secret query strings in shared logs. The local sample prints request lines only for known synthetic URLs. In a managed environment, decide which paths and identifiers operators need, how to protect those logs and what fields should be withheld. If the report redirects to the wrong scheme while the data is correct, check the documented external URL and safe forwarded-metadata path before rewriting every redirect. The issue can lie in which connection's facts the app used.

Lab four. Separate an unavailable target from a slow target

Open the private Nginx exercise, restore the working target with its trailing slash and confirm the direct and routed student list. First run the controlled slow request. The fixture waits for three seconds before sending a complete JSON response. The direct request allows five seconds. Nginx in this lab is set to wait at most one second for a read when the upstream has sent nothing. The comparison demonstrates a timer at the front, rather than a general rule that a request lasts no more than one second.

curl --noproxy '*' --max-time 5 --include http://127.0.0.1:18961/slow
curl --noproxy '*' --max-time 5 --include http://127.0.0.1:18960/training/slow
tail -n 10 logs/access.log
tail -n 10 logs/error.log

Expect the direct check to return 200 after the wait, and the front request to return 504 with an upstream timeout in the error log. The Nginx read timeout applies between successive read operations. A stream making progress can take longer than that interval overall. A front's connect timeout concerns starting a connection. A client timeout is yet another clock. A busy application or database can run up against a front limit while being perfectly reachable. Identify where the wait is before changing a value. Increasing it everywhere may keep work around longer without increasing the app's ability to satisfy it.

Second, stop the Python fixture from its own terminal using Control-C. Keep the private Nginx worker running. Again request the direct and prefixed student URLs. The direct curl should fail to connect to that known unused loopback port. Nginx should return 502 for the forwarded request in this particular configuration, and the private log should show a refused connection. The /site-check still succeeds. That combination tells us the front is alive but cannot open this upstream connection. Other deployments can have different causes for 502, including an invalid response, a closed connection or a front policy failure, and status by itself cannot select the cause.

curl --noproxy '*' --max-time 5 --include http://127.0.0.1:18961/api/students
curl --noproxy '*' --max-time 5 --include http://127.0.0.1:18960/training/api/students
curl --noproxy '*' --max-time 5 --include http://127.0.0.1:18960/site-check
tail -n 10 logs/error.log

Finally, restart the same practice app in its terminal and repeat the two successful report requests. Reuse the original config without changing the front to make clear which controlled action restored service. If your environment has a distinct app health endpoint, use a GET that matches its route handler. A command such as curl -I sends HEAD. It can be helpful, but a status for HEAD does not always verify the GET answer body, expected list or behavior of the route. Once testing is complete, stop the private front and app from their own terminals. Confirm that the practice listener ports have closed and remove or archive only the workspace you made. Record the statuses and log reasons in a short table for later review.

Carry the local evidence into an approved hosted change

Write down the deployed listener, virtual hostname, upstream service and routes before opening an editor. If there is an existing setup, obtain its effective configuration and capture the approved prior files and permissions. Nginx includes, Apache enabled sites and service manager options depend on the installed package and operating system. Decide which single virtual host entry to edit and how to restore it. Confirm that a default or catch-all handler belongs to your change before editing it. This makes the plan workable on a shared host where other names should continue serving independently.

Check the app's direct read with the exact target address from the planned configuration. If your shell can connect but the front process cannot, compare the front's runtime identity and isolation. An operating system with SELinux enforcing can deny the connection based on its policy even when ordinary network configuration permits it. Use the authorized logs or operator workflow to confirm the precise denial. Ask the administrator for the scoped policy required by the actual deployment. An unconditional broad persistent setting change is poor proof of the observed cause, and can affect other web processes. A sandbox, network namespace, host firewall, address family change or container setting may explain similar symptoms. Record evidence before adjusting any boundary.

Have the front parse the intended configuration with its normal executable and flags. Deploy only through the approved service mechanism, then read reload status and the front's logs. A syntactically valid candidate can serve the wrong host, send a route to the wrong port or leave clients with broken links. Check an existing unaffected path and the new site's critical routes with the full hostname, TLS verification and known markers. In a managed deployment, check redirect destination and scheme, response status and content type, and the report visible to the intended user. Confirm the upstream response evidence and retain the plan for restoring both route and app revisions if targets changed together.

For a first hosted change, a named staging hostname is simpler than repointing a busy website in a hurry. Use host-aware probes and proper TLS verification so the check resembles a real user's request. If the subsequent rollback restores the front config, it must restore a target that is also still available. Suppose service version B runs on a new port and the previous port is closed. Restoring a config that points to version A cannot help until its target is available and compatible. Record coupled settings and validate the expected report after restoration. Keep the progress record to actual evidence such as front resolved, TLS trusted, prefixed report 200, two expected synthetic rows.

Read one traffic observation across both servers

Use the successful course request as the first row in a worksheet. Record the front hostname and port, the exact route entered, the expected upstream address and intended URL. Then fill in the measured front status and the upstream status shown in the lab logs. The front marker has no upstream status, because Nginx generated it itself. A proxied student query has both statuses, and the teaching app records the received path in its terminal. A front 404 with no upstream and an application 404 with upstream 404 can look identical in a browser tab. Those rows lead to different places to investigate.

The total request timing and upstream timing help interpret the slow experiment. The front's request time measures work from its perspective, including time associated with the client connection. The upstream response timing identifies the front's observations of that application request. Similar numeric values can come from very different paths. A direct curl prints its own measurement, which includes the client's observations. A timeout from a reverse proxy does not guarantee a worker stopped computing immediately. A real app that accepts work with side effects needs a defined outcome and retry policy. This fixture's slow operation only waits and sends a read-only status, so repeating it has no stored effects.

If the single-node course configuration later spreads across two servers, write the trust and timing choices again. Is the target still loopback? What does each peer see? Where are the health checks evaluated? What DNS resolution and encryption apply to the new upstream? Which listener is responsible for route-specific authorization? Record which deployment invariants changed. Reusing a prefix rule can be reasonable if the new app receives the same paths. Reusing all network and metadata assumptions just because the config looks similar can produce confusing operator evidence.

Result from the public or front testCompare nextPlausible route to a repair
Known default page returns 200Requested authority and selected virtual hostTest the exact intended host before changing application code.
Prefixed HTML succeeds, asset 404sActual asset URL in browser network activityAlign generated links, public prefix and app routes.
Front 502 while local app supports GETEffective target address and port, front's logs and execution contextCheck protocol, target or the scoped host policy according to evidence.
Front 504 during the slow lessonDirect response timing and configured waiting phaseTrace and bound slow upstream work before setting timeouts deliberately.

Explain reverse proxy design in an interview

What does the reverse proxy add to this hosting design?

It gives the course an agreed front name and listener, chooses the configured upstream for each route and forwards HTTP requests. The same front can handle TLS at that boundary and collect suitable access evidence. The application checks and authorizes its operations independently. In the one-host design, the secondary listener only needs loopback connectivity. The front-to-backend transport and reachability must be revisited if the app moves to another machine or network namespace.

Where do you look when Nginx returns 404?

First identify which component produced the response. Check the requested host, exact path, private front logs and a matching direct application GET. In the lab, a missing front path produces a text marker without an upstream status. A matching front route can still receive an app 404 with an upstream JSON marker. Fix the selected front rule or app route according to which boundary failed.

What changes if the proxy target ends with a slash?

In the plain Nginx prefix rule shown, the slash is the replacement URI. A front request under the training prefix reaches the app at the remaining root-based path. Without a URI on the target, the simple version leaves the full request path in place. A written mapping table is safer to review than memorizing that a slash always fixes an app.

How do you troubleshoot a front 502 with an apparently running service?

Confirm whether the application actually accepts the exact upstream address and port, responds to the expected method and speaks the configured protocol. Compare the front process's own error evidence with a direct request and check service or platform constraints if the observations differ. A supervisor saying its process is running does not show the selected listener, ready dependencies or valid HTTP response.

Why are forwarded fields a deployment decision?

The app observes the immediately connected peer. Other attributes may be relayed by explicitly trusted intermediaries. Identify which relays can reach the app and where each metadata value comes from. Then configure the front to set the appropriate fields and the framework to trust only the intended source and order. This is especially important when adding or removing an intermediate load balancer.

Test the evidence before selecting a fix

  1. The front responds at the expected IP but shows a different website. Which check comes first?

    Show answer

    Request the intended hostname and inspect the selected virtual host. Several sites can share a port, and an IP-only request can reach the default one.

  2. In the shown Nginx rule with a trailing target slash, where is /training/api/students?city=Pune sent?

    Show answer

    It becomes the upstream request /api/students?city=Pune. The replacement URI substitutes the matched prefix and leaves the query in this simple rule.

  3. The app reports the wrong upstream path with its own 404. Did the proxy connect successfully?

    Show answer

    Yes in this recorded request. The upstream app emitted an identifiable reply. Fix the route contract or its implementation instead of opening more network ports.

  4. In the fixed-delay lab, why does the direct call work while the front returns 504?

    Show answer

    The direct client waits long enough. The front's read timer expires while the fixture is silent. Those are separate connections and settings.

  5. Should you add an EC2 inbound rule for a same-host app dedicated to the front proxy?

    Show answer

    In this topology, its app listener is IPv4 loopback and the front reaches it locally. Permit only the intended front listener and source under the deployment's network plan.

Revision cards

Two connections
The client talks to the site front. The reverse proxy opens a distinct connection to the backend application.
Virtual host
Host selection determines which site's rules receive the request when listeners are shared.
Incoming prefix mapping
Write down public and upstream paths. Compare behavior for the route, query, follow-up links and missing path.
Redirect translation
Nginx and Apache can adjust selected response redirect headers. Verify generated page links and cookie behavior separately.
Forwarded metadata
Supply only needed facts from known hops. Configure app trust to match the way traffic can actually reach the deployment.
Proxy diagnostics
Compare direct GET, front GET and both logs. Status and timing indicate where to investigate when interpreted with route evidence.

Design a prefix migration for the club's workshop reports

Assume the club wants to move the practice link from /training/ to /workshops/. Build a tiny acceptance table before modifying the lab. Cover the new HTML route, the new data route with a query, an internal redirect rewritten to the new front prefix, an app-defined missing route and the unchanged /site-check. Write the upstream path and expected body marker for each. Decide deliberately whether the old prefix remains temporarily available, returns a redirect, or is retired. If clients use fetch calls or cookies, add explicit checks for those paths too.

Use a copy of the private Nginx configuration to implement the smallest route change. Validate it and rerun the table against that exact private copy. If the prefix mapping fails, restore the original file, validate again and verify the original report. A good record includes the failing result, the restored result and the narrow difference between configurations. Shut down the owned lab processes when finished. A real site migration would also define how readers discover the new path and how long the old address remains part of the service contract.

Official references