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

Chapter 8: Configuring Nginx and Apache

AWS Cloud

8.8 Useful everyday configurations

Friends, these small configs are useful every day – the www redirect, the HTTPS redirect, hiding the version, the upload limit, a password and compression. Check the intended site, scope and module before adapting a setting.

Redirect www to the main domain (or the reverse)

server {
    listen 80;
    server_name www.example.com;
    return 301 http://example.com$request_uri;
}
<VirtualHost *:80>
    ServerName www.example.com
    Redirect permanent / http://example.com/
</VirtualHost>

Redirect HTTP to HTTPS

Certificate tools can offer a redirect option, depending on how they are used. In the intended port-80 site, an explicit fixed target can be return 301 https://example.com$request_uri; in Nginx or Redirect permanent / https://example.com/ in Apache. Test the first Location and HTTPS destination separately.

Reduce displayed version details

# Nginx: inside http { } of nginx.conf
server_tokens off;
# Apache: place ServerTokens in the intended global configuration
ServerTokens Prod
ServerSignature Off
# Inspect the include and active site settings for your installation

Use a controlled request for the intended hostname and route. Inspect the Server header and any applicable generated error page. A proxy can supply a different header.

Increase the upload limit

Nginx supports client_max_body_size in HTTP, server or location scope. Choose a limit justified by the intended route. For PHP, check the effective upload_max_filesize and post_max_size, including other form fields and encoding overhead.

Password-protect a folder (basic auth)

Use the approved credential-management workflow to prepare the password file outside the public document tree. The htpasswd -c option creates a new file and can rewrite a file that already exists. Use the appropriate update operation for an existing database, keep permissions narrow, and send real credentials only over verified HTTPS.

location /admin/ {
    auth_basic "Restricted";
    auth_basic_user_file /etc/nginx/.htpasswd;
}

Apache can use AuthType Basic, a realm, a provider file and Require valid-user in the chosen authorization context with the required modules. Both examples require an approved encrypted route for real credentials because Basic authentication uses reversible Base64 encoding.

Enable compression

# Nginx example for a selected public-asset location
gzip on;
gzip_types text/css application/javascript application/json image/svg+xml;

Apache can apply the DEFLATE filter by media type using AddOutputFilterByType. Check for both mod_deflate and mod_filter in the candidate configuration, then test responses on the intended scope.

Ravindra Bagale's Tip

Many students use basic auth over plain HTTP. Remember: the basic auth password only travels as base64, not encrypted – so never use it without HTTPS. And after server_tokens off;, check the Server: header with curl -I.

Lab

The isolated lab below checks the correct site and validates a redirect, compressed and plain response, cache headers, and accepted and rejected upload bodies. It also shows which server details the selected listener sends.

Tie each web server setting to a visible response

A dairy's catalog site has the same product details on a new main address and an old link from a newsletter. Customers need the old link to keep working. On slow connections they want product text to load quickly. Staff also need to upload reports, but the application should reject an oversized submission cleanly. These are several different requirements. A redirect tells a client where to ask next. Compression changes the bytes sent for a response. Cache controls describe when an earlier response can be reused. An upload limit constrains incoming request bodies. A good configuration review names the request, the expected response and the rule responsible for each requirement.

Begin with one change and one comparison request. Record the same method, hostname and path before and after the work. Add a control that should remain on the existing behavior. For example, check that the old catalog route redirects to the right target and that a normal static file still returns successful content. Check both requests with the same known listener. A development environment whose default shows a simple home page might otherwise make every test look successful without serving or protecting the route you intended.

Several of these behaviors are expressed in HTTP headers, named pieces of information sent alongside the method, status and body. A response can specify where to redirect, how its body was encoded and how long a cache may keep it fresh. Inspect the initial status and headers without automatic following on your first redirect test. Read the body separately when checking whether bytes were successfully served or rejected by the expected component. An HTTP response can be generated by a browser-facing proxy, an origin web server or an upstream application. Their logs and appropriately scoped markers help identify which component made the decision.

Redirect to a known destination and test both requests

A redirect is an HTTP response whose status and Location header instruct a client about another destination. A canonical hostname is the one the site prefers visitors to use. A supported alternate can send a redirect to that fixed name. A URL's path and query can be retained when the new route understands them, or mapped deliberately when its structure differs. Avoid reflecting a name from an untrusted Host value into the destination when the service should send visitors to an expected site. Keep unknown host behavior separate from your intentional alternate redirect.

Choose a redirect status according to the change. Temporary redirects suit a preview or a validation phase. Permanent redirects can be reused by clients and caches, so introduce one when the route is confirmed. The historic handling of 301 and 302 permits some clients to change a POST into a GET on following the response. The 307 and 308 forms preserve the original method. For an ordinary catalog link the client uses GET. For routes with request bodies, think about whether sending that same method and body to a new destination is appropriate. A redirect is not an implementation of upload authorization or a signal to send private data to an unrelated domain.

Make two observations. Suppose the old link is /old-catalog?from=newsletter and the intended new path is /catalog.txt?from=newsletter. The first request should return the selected redirect status and that exact approved target. A second request to the destination should return the expected contents, such as the marker for the current public catalog. If the first target loses the query value, the final page could still appear to work while losing the input the owner wanted. If the destination redirects again, state whether that second hop is expected. When testing with curl, save the first response separately and only then test following it when useful.

A redirect from HTTP to HTTPS is also two requests. The HTTP server sends an HTTPS Location. The next request requires a working TLS connection and a certificate covering the actual target host. A TLS certificate on a different hostname is insufficient. An alternate hostname reached directly over HTTPS first needs a valid TLS connection for the alternate even if every request afterward redirects. Certificate management tools may offer a redirect configuration, depending on the invocation and environment. Verify the deployed rule and the certificate rather than assuming automated certificate issuance created all the public routes. The loopback lab uses only plaintext test content and exercises a path redirect, without pretending that it verifies public HTTPS.

Set cache behavior and compression for the intended content

A cache stores a response so a later request can receive data without downloading it from the same upstream again. A freshness lifetime establishes when a stored response can normally be reused without checking, subject to the request and the cache's rules. For example, the lab gives a public asset a one-hour maximum age. A revision of that asset under the same URL might not appear immediately in a browser that already saved it. For a release with content-hashed filenames, a new HTML file can refer to a new filename while existing asset URLs retain a longer useful lifetime. Confirm that your design actually changes URLs when content changes before applying a long duration broadly.

Read cache directives by effect. The max-age directive defines freshness for a number of seconds. A no-cache directive commonly permits a response to be stored but requires validation before reuse. A no-store directive tells caches not to store the response under normal compliant behavior. A private directive excludes shared caches while allowing an eligible private cache to store it. These concepts are different from server-side browser history or application memory. Apply a suitable policy to changing pages and sensitive or user-specific responses. Do not assume an entire directory can use one long lifetime just because some of its files are images or styles.

Response compression encodes the same content using fewer bytes for transit. A client announces acceptable content encodings in Accept-Encoding. If Nginx sends compressed content, Content-Encoding identifies the resulting encoding, such as gzip. The decompressed bytes should preserve the original document. File type and minimum length conditions influence when gzip applies. For example, the lab enables it only on a public asset path and includes text files in the eligible types. Compression can reduce transfer for repetitive text, while a small file or data already compressed may see little gain. The process incurs computation, so choose and measure the scope rather than enabling every possible type by habit.

When responses vary by accepted encoding, a cache needs that input to select the correct stored variant. The Vary header can declare Accept-Encoding as one such input. Inspect the gzip and plain responses side by side. The gzip response should carry a correct Content-Encoding, and the Vary setting should apply as configured. Compare bytes after decoding rather than looking only at the file extension. A text file with a compressed transfer remains text after it arrives and is decoded. In security-sensitive application responses, review compression policy, particularly where secret values might be reflected alongside user-controlled content. This exercise compresses only static public fixture bytes.

Match an everyday setting to a positive and a control request
RequirementPositive evidenceControl
Redirect old catalog pathInitial redirect status and accurate LocationDestination body and unrelated asset response
Compress the asset for compatible clientsgzip coding and decompressed bytes matching the sourceSame body for an identity request without gzip coding
Cache only suitable content for an hourAsset freshness header with 3600 secondsSeparate catalog no-cache policy
Reject submissions beyond the configured limitLarger request receives 413 without reaching the handlerSmall request reaches the expected local program

Diagnose body limits, authentication and server headers

An upload is usually part of a request body, which is the data carried after the request headers. A request-body limit controls how much data a component accepts for that request. A web server, intermediary and upstream application can each set a limit. For example, Nginx can apply client_max_body_size to a site or specific route. A PHP runtime may also impose a maximum file upload size and a separate maximum POST body size, which needs to account for other form fields and multipart overhead. A reverse proxy or load balancer can add another restriction. Diagnose the nearest component demonstrably rejecting the request before increasing any setting.

Suppose a 512-byte experimental submission reaches the upload program but a 2048-byte submission to the same route returns 413. In the lesson’s fixture the Nginx route allows a one-kibibyte raw body. A kibibyte is 1024 bytes. The upstream reports byte counts for accepted bodies, and a local access trace gives a separate assertion that the larger body never reached it. In a real upload form the request body can contain more bytes than the file because metadata adds overhead. Measure the actual request size and keep scope specific to the allowed upload endpoint. A high limit can change memory, storage and timing requirements even for a syntactically correct server.

HTTP Basic authentication is a web-server authentication scheme that can challenge the client before serving a protected path. A 401 can include a WWW-Authenticate header announcing the required scheme and realm. Its credentials use a reversible base64 representation, so use it over appropriately configured TLS for real credentials. Protect the password database file from public download and inappropriate access. A utility such as htpasswd can create a new file or update an existing account, but its create option can rewrite an existing file. Use the approved credential workflow and avoid showing actual passwords in command arguments, page content or logs. This lab does not send credentials over its plain local HTTP listeners.

An advertised server version is a different question. Nginx can reduce emitted version details with server_tokens, and Apache can control its server header and generated signatures with server-wide and applicable signature settings. A browser-facing proxy may supply another header or generated response. Verify the exposed endpoint and relevant response types instead of relying on a sample Header line. Reducing visible version details has a narrow purpose. Updating software and configuring actual access controls are separate responsibilities. Compare headers for a service you own and avoid interpreting a product name as the exact version or complete inventory of its stack.

Lab to compare redirects, encodings, freshness and upload results

Use a disposable Bash shell as a regular account with Nginx, Python 3, curl and gzip installed. The fixture opens two temporary listeners on IPv4 loopback only. Nginx receives the test HTTP requests at port 18890, and a small Python program listens at 18891 for the upload route. Pick two different free high ports and replace all corresponding references if there is an existing listener. There is no need for an EC2 security group change or package service action. The experiment uses files created in its own temporary directory and a bounded synthetic submission. Do not use real credentials or user files in the demo.

The first block writes a plain catalog marker, a larger repetitive public text asset, and two request bodies. The smallest body is 512 bytes. The other is 2048 bytes and intentionally exceeds the private test limit. Two different temporary processes will read this location. The cleanup routine remembers the correct shell-owned process identifiers and removes the generated root at the end. This way a partially started experiment cannot require restarting a live system service.

if [ "$(id -u)" -eq 0 ]; then
  printf 'Use a regular practice account.\n' >&2
  exit 1
fi
nginx_bin=$(command -v nginx) || exit 1
http_lab=$(mktemp -d /tmp/rb-http-settings.XXXXXX) || exit 1
ng_pid=
up_pid=
settings_cleanup() {
  if [ -n "$ng_pid" ] && kill -0 "$ng_pid" 2>/dev/null; then
    kill -QUIT "$ng_pid"
    wait "$ng_pid" 2>/dev/null || :
  fi
  if [ -n "$up_pid" ] && kill -0 "$up_pid" 2>/dev/null; then
    kill "$up_pid"
    wait "$up_pid" 2>/dev/null || :
  fi
  case "$http_lab" in
    /tmp/rb-http-settings.??????) rm -r -- "$http_lab" ;;
  esac
}
trap settings_cleanup EXIT
mkdir -p "$http_lab/public/assets"
printf 'dairy-catalog-current\n' > "$http_lab/public/catalog.txt"
python3 - "$http_lab" <<'PY'
from pathlib import Path
import sys
base = Path(sys.argv[1])
(base / "public/assets/details.txt").write_text(
    ("Local dairy offers fresh milk and yogurt each day.\n" * 120), encoding="utf-8"
)
(base / "small.body").write_bytes(b"x" * 512)
(base / "large.body").write_bytes(b"x" * 2048)
PY
wc -c "$http_lab/public/assets/details.txt" "$http_lab/small.body" "$http_lab/large.body"

The Python server is an observation tool for the experiment. It does not implement a real upload application. One GET endpoint announces readiness once the private server started. The upload handler reads the number of bytes in the Content-Length field on the synthetic POST, records the received count in its private log and answers with that number. The incoming bodies are plain repeated bytes. The handler sets a timeout, restricts the demonstration's accepted size and discards the body after counting. The key evidence is whether an application received a request and how many bytes arrived.

cat > "$http_lab/upstream.py" <<'PY'
from http.server import BaseHTTPRequestHandler, HTTPServer

class Counts(BaseHTTPRequestHandler):
    def respond(self, code, text):
        data = text.encode("utf-8")
        self.send_response(code)
        self.send_header("Content-Type", "text/plain")
        self.send_header("Content-Length", str(len(data)))
        self.end_headers()
        self.wfile.write(data)

    def do_GET(self):
        if self.path == "/ready":
            self.respond(200, "upstream-ready\n")
        else:
            self.respond(404, "unknown\n")

    def do_POST(self):
        if self.path != "/upload":
            self.respond(404, "unknown\n")
            return
        try:
            size = int(self.headers.get("Content-Length", "-1"))
        except ValueError:
            size = -1
        if size < 0 or size > 4096:
            self.respond(400, "unsupported fixture size\n")
            return
        self.connection.settimeout(4)
        received = len(self.rfile.read(size))
        print(f"accepted bytes={received}", flush=True)
        self.respond(200, f"accepted bytes={received}\n")

    def log_message(self, fmt, *args):
        return

with HTTPServer(("127.0.0.1", 18891), Counts) as server:
    server.serve_forever()
PY
python3 "$http_lab/upstream.py" > "$http_lab/upstream.log" 2>&1 &
up_pid=$!
up_ready=''
for attempt in 1 2 3 4 5 6 7 8 9 10; do
  if ! kill -0 "$up_pid" 2>/dev/null; then break; fi
  up_ready=$(curl --noproxy '*' --max-time 1 -fsS http://127.0.0.1:18891/ready 2>/dev/null) || :
  if [ "$up_ready" = upstream-ready ]; then break; fi
  sleep 0.2
done
if ! kill -0 "$up_pid" 2>/dev/null || [ "$up_ready" != upstream-ready ]; then
  cat "$http_lab/upstream.log" >&2
  exit 1
fi

Write the Nginx configuration with each policy attached to an intended route. The old catalog path redirects temporarily to the known new path and appends the original query if present. The ordinary catalog is a changing page with a no-cache header. The public asset prefix has one hour of freshness and offers gzip for eligible text. The exact upload route forwards to the private Python service after enforcing the limited body size. A named test site is used in the requests. All log, PID and runtime paths live under this generated prefix. Read the candidate response rules before running the test and starting the isolated process.

cat > "$http_lab/nginx.conf" <<'NGINX'
worker_processes 1;
pid nginx.pid;
error_log error.log notice;
events { worker_connections 32; }
http {
    server_tokens off;
    default_type text/plain;
    client_body_temp_path body;
    proxy_temp_path proxy;
    fastcgi_temp_path fastcgi;
    uwsgi_temp_path uwsgi;
    scgi_temp_path scgi;
    access_log access.log;
    server {
        listen 127.0.0.1:18890;
        server_name catalog.test;
        root public;
        location = /old-catalog {
            return 302 /catalog.txt$is_args$args;
        }
        location = /catalog.txt {
            add_header Cache-Control "no-cache" always;
            try_files $uri =404;
        }
        location /assets/ {
            expires 1h;
            gzip on;
            gzip_types text/plain;
            gzip_min_length 128;
            gzip_vary on;
            try_files $uri =404;
        }
        location = /upload {
            client_max_body_size 1k;
            proxy_pass http://127.0.0.1:18891;
        }
    }
}
NGINX
"$nginx_bin" -e stderr -p "$http_lab/" -c "$http_lab/nginx.conf" -t || exit 1
"$nginx_bin" -e stderr -p "$http_lab/" -c "$http_lab/nginx.conf" -g 'daemon off;' &
ng_pid=$!
for attempt in 1 2 3 4 5 6 7 8 9 10; do
  if [ -s "$http_lab/nginx.pid" ]; then break; fi
  if ! kill -0 "$ng_pid" 2>/dev/null; then break; fi
  sleep 0.2
done
if ! kill -0 "$ng_pid" 2>/dev/null ||
   [ ! -s "$http_lab/nginx.pid" ] ||
   [ "$(tr -d '[:space:]' < "$http_lab/nginx.pid")" != "$ng_pid" ]; then
  printf 'The isolated Nginx listener did not start. Check its log.\n' >&2
  if [ -r "$http_lab/error.log" ]; then tail -n 8 "$http_lab/error.log" >&2; fi
  exit 1
fi

The proof begins with the initial redirect and its destination. The next small wrapper preserves hostname and port while forcing the loopback address. The first transfer prints a redirect status and Location with the copied query. The direct catalog transfer should return 200, the catalog body and its no-cache header. The configured server header in this test identifies Nginx without its numeric release. It should be interpreted as evidence of the selected response policy in this instance, not as proof a web server version is hidden in every possible response.

request() {
  curl --noproxy '*' --max-time 5 -sS --resolve catalog.test:18890:127.0.0.1 "$@"
}
request -i 'http://catalog.test:18890/old-catalog?from=newsletter'
request -i 'http://catalog.test:18890/catalog.txt?from=newsletter'

For the asset, request an identity transfer and a gzip transfer while keeping the URL fixed. By sending the Accept-Encoding header directly, curl saves the encoded gzip representation without implicitly decoding it. Decode that file in the temporary directory, compare its bytes with the plain form, and read the wire file sizes. Curl has already handled HTTP framing in these files. Those sizes describe the stored identity and compressed representation bodies, with response headers excluded. The first body should be larger because the source material was deliberately repetitive.

request -H 'Accept-Encoding: identity' -D "$http_lab/plain.headers" \
  -o "$http_lab/plain.body" http://catalog.test:18890/assets/details.txt
request -H 'Accept-Encoding: gzip' -D "$http_lab/gzip.headers" \
  -o "$http_lab/compressed.body" http://catalog.test:18890/assets/details.txt
grep -Ei '^(HTTP/|Content-Encoding:|Cache-Control:|Vary:|Expires:)' "$http_lab/plain.headers"
grep -Ei '^(HTTP/|Content-Encoding:|Cache-Control:|Vary:|Expires:)' "$http_lab/gzip.headers"
gzip -dc "$http_lab/compressed.body" > "$http_lab/decoded.body" || exit 1
cmp "$http_lab/plain.body" "$http_lab/decoded.body" || exit 1
wc -c "$http_lab/plain.body" "$http_lab/compressed.body"

The compressed response should show gzip, and both public representations should show the chosen freshness lifetime. The Vary setting tells a cache that it needs to distinguish the accepted encoding. In an actual proxy deployment, another hop might recompress a response or use a separate cache policy. The isolated lab has no such extra hop. This controlled comparison confirms the configuration on the listener you started. It also avoids confusing a pretty compressed file name with proof the response was encoded on the wire.

Finally compare a small and large POST to the exact same upload URI. Curl's data-binary option reads the file bytes and sends them as a request body. The route-specific threshold accepts the smaller body and rejects the larger before the Python count. The first response should report accepted bytes equal to 512. The next should carry HTTP 413. Inspect the local Python log and the Nginx access log. Only the successful count should appear in the upstream output. A single 413 header alone would not identify which component imposed the limit in a multi-component route.

request -i --data-binary "@$http_lab/small.body" http://catalog.test:18890/upload
request -i --data-binary "@$http_lab/large.body" http://catalog.test:18890/upload
cat "$http_lab/upstream.log"
tail -n 6 "$http_lab/access.log"

Save your observed status, header and body differences before teardown. The cleanup stops Nginx first so its requests no longer reach the counting service, then stops the child Python process. Its final existence test confirms the scratch directory disappeared. If you stop at an earlier error, leave the disposable shell so its registered routine runs. Record which checks had already passed before the error, because a partially working lab does not prove that the next independent process or HTTP policy worked.

settings_cleanup
trap - EXIT
test ! -e "$http_lab" && printf 'HTTP settings lab removed.\n'

Use a conditional request to see how no-cache can still reuse bytes

The catalog page has a no-cache policy because its contents may change while the URL stays the same. No-cache means a saved response must be validated before reuse, subject to the applicable cache rules. It does not mean every repeat requires downloading the body again. Start with a normal request for the catalog while the lab is serving the original file. Its response contains an entity tag, or ETag, which identifies the selected representation for comparison. Treat the tag as an opaque value that belongs to that response. Preserve its quotes. Do not try to infer what every web server uses to generate it.

The second request sends the received tag in If-None-Match. This is a conditional request, meaning the method's result depends on a comparison involving the current representation. For this GET, the fixture should find that the saved tag still matches and return 304 Not Modified. The status conveys that the client can reuse its saved body for the selected representation. The 304 itself does not provide a new catalog body. The observed still-valid response is an example of checking before reuse.

cache_url='http://catalog.test:18890/catalog.txt'
request -D "$http_lab/catalog.headers" -o "$http_lab/catalog.saved" "$cache_url" || exit 1
saved_tag=$(awk 'tolower($1) == "etag:" { sub(/\r$/, "", $2); print $2; exit }' \
  "$http_lab/catalog.headers")
test -n "$saved_tag" || exit 1
printf 'Saved tag %s\n' "$saved_tag"
request -H "If-None-Match: $saved_tag" -D "$http_lab/conditional.headers" \
  -o "$http_lab/conditional.body" "$cache_url" || exit 1
head -n 1 "$http_lab/conditional.headers"
test ! -s "$http_lab/conditional.body" || exit 1
cat "$http_lab/catalog.saved"

Run this block before cleanup. It saves headers and catalog bytes on separate paths. The awk expression finds the entity tag regardless of header capitalization and removes only the carriage return from that field. The second request does not replace the saved original, because its output belongs to another file. The body check accepts an absent or zero-length file for the recorded conditional response. The final cat shows the earlier original content you could reuse after validation. That saved text is not a body Nginx transmitted with the 304.

For a student follow-up, make a clear content change inside the disposable installation and repeat the same conditional request using the old tag. On this fixture, give the changed file a different length as well as different text to make its validator change easy to observe. A correct fresh response should now carry 200 and the new marker, because the old supplied tag no longer describes the current representation. In a real application, validators should change whenever its representation requires new bytes. If a manual file replacement can keep all metadata used to generate a validator the same, use the deployment's expected metadata and cache strategy rather than assuming the origin will always detect the bytes changed.

Connect this to the asset example. The public asset can have a longer freshness lifetime. While its response remains fresh, ordinary caches can often reuse it without this conditional request, subject to policy. The catalog can instead validate before reuse, reducing stale content risk while still avoiding another body transfer when possible. Your test output separates the directives from the consequences. Save the initial status and tag, filtered cache headers, subsequent 304 and the already stored body. Compare them with the changed response after the follow-up.

Test the exact limit and interpret a comparison request

The first two uploads bracket the configured limit widely. For a boundary check, make one more request exactly at one kibibyte and one just above it. Generate both files before running the shown cleanup, while the same private listener and counting server remain in service. This asks a sharper question: does the configured threshold admit an equal body size, and does adding one byte cross it? Keep the same URL, method and transfer routine. Only the body length should change.

python3 - "$http_lab" <<'PY'
from pathlib import Path
import sys
base = Path(sys.argv[1])
(base / "at-limit.body").write_bytes(b"x" * 1024)
(base / "over-limit.body").write_bytes(b"x" * 1025)
PY
request -i --data-binary "@$http_lab/at-limit.body" http://catalog.test:18890/upload
request -i --data-binary "@$http_lab/over-limit.body" http://catalog.test:18890/upload
cat "$http_lab/upstream.log"

The body at the limit should receive HTTP 200 and the exact byte count. The body just over should receive 413 and should not add an accepted count to the Python log. Recapture the plain and compressed asset if you want evidence after these extra POSTs. Those GET requests should keep their original cache and encoding policies because the changed variable was a body affecting a different route. If the result differs in a real web form, include headers and form overhead in the analysis. Uploading a file of a given size inside multipart form data can create a larger complete body than the direct file bytes used here.

In the verified run the public fixture had 6120 bytes uncompressed and 129 bytes saved as the gzip response body. That unusually large reduction reflects the repeated identical source line, and the exact compressed size can vary by implementation or settings. It is an exercise in interpreting measurements, not a benchmark. The log may report a different number of sent bytes from the saved body because transport or server logging details differ. The stronger invariant is that the decoded bytes match the plain content and the response correctly labels the encoding.

Use the headers, logs and body to narrow a release problem

Suppose an operator turns on compression but sees plain content on a test. Before changing the config again, inspect what the client offered. Some inspection tools send an appropriate header only when asked. A HEAD request is useful for comparing headers but does not deliver the response body for a byte comparison. The effective location must also allow compression for the returned media type and satisfy the implementation's requirements. A tiny body may be smaller than the configured threshold. An already encoded upstream response might not undergo the same filter. Read the actual request and response before deciding an eligible representation was missed.

When the gzip response arrives but a user sees unreadable data, check whether the body matches its stated encoding. A proxy may have re-encoded data or passed a stale response. If clients can request multiple encodings, compare the response Vary selection observed on the relevant path. An HTTP client can ask curl to decode a compressed response for ordinary use. In the lab we saved encoded bytes intentionally so we could prove that decoding produces the same file. Choose the right observation. An already decoded file could be larger than the compressed bytes transferred, even when the compression feature worked as designed.

The cache configuration can explain why a direct request and a browser differ. A cache may reuse a response while it is fresh. A validator is metadata that lets a recipient ask whether a stored response is still usable, such as an entity tag or last-modified time. After a response requires revalidation, a successful validation can return a response such as 304 so the cache may reuse the stored body. A header-only validation response does not indicate a broken file delivery. Compare the selected endpoint, response headers and whether a new origin request was made. Avoid giving one-hour freshness to frequently changing HTML or user-specific data simply because it belongs to the same site as stable assets.

A redirect can also be remembered. If a test jumped to an earlier destination after a server rollback, inspect a fresh transfer and an ordinary client separately. A previously saved permanent redirect can behave differently from a fresh response. Verify that the live first-hop status and Location came from the intended host and scheme. Preserve the exact route and query as they were typed. When a redirect is generated by a proxy or certificate integration, the origin's configuration alone may not produce the response you see from the public route.

Suppose a test first fetched a public product photo and then loaded an account-specific report under the same broad location prefix. A cache rule appropriate for the photo need not be appropriate for the report. Find out which response type the URL can produce and whether its contents depend on identity. Read the headers actually emitted by the cache-facing route rather than inferring them from one origin line. Apply policy at an appropriate narrow location or application handler and make separate tests for public and authorized responses. A cached report is not a useful performance win if another visitor can receive it. Use synthetic account fixtures only in an authorized setting when validating the distinction.

Look at which response statuses get the policy as well. A response for an absent asset can come from a different location or carry different caching behavior from a successful file. If a deployment creates a new asset after a request for that filename failed, an intermediary might still serve the saved error according to its own rules. Compare a known existing asset, an intentionally missing one and an updated reference using the ordinary public route. A configuration listing only the successful request's desired headers says little about those negative paths. Record status and headers together for these controls. The lab uses simple positive assets and a fresh origin so successful compression and expiry properties are easy to identify.

For request-size failures, measure which component reports the error. In the lab the upstream logs one accepted body per request it received. On an approved test site, correlate a clearly identified request with each applicable proxy, origin and application log. If the HTTP server never forwarded it, the runtime configuration cannot make that particular attempt succeed. If the proxy forwarded it and the application rejected it, inspect the upload and POST limits in effect for the actual application runtime. Raising config globally as a first move can permit larger requests on unrelated routes and place unexpected load on storage or memory.

For a protected page, a successful redirect does not demonstrate access control. Test the expected anonymous response, the approved authenticated response and a neighboring public path. Keep the protected request over its approved encrypted route. Browser-side caches or an upstream proxy need appropriate policy too. Inspect the host, path and final error status, rather than inferring access from how a dialog looked. The lab avoids transmitting credentials because its purpose is to observe ordinary HTTP features separately.

Translate the requirements into Apache settings carefully

Apache supports similar behaviors through different directives and modules. The module and package settings need to exist where the candidate is parsed. A redirect can be implemented with Redirect from mod_alias when a simple path mapping fits. A Redirect rule has its own matching and target rules, so verify the initial status, path and query rather than assuming it is a text replacement for an Nginx return. For more involved rewriting, read the appropriate module's semantics. Keep redirects tied to names and routes they are meant to change.

Compression commonly uses the DEFLATE output filter from mod_deflate. A configuration that selects media types through AddOutputFilterByType also uses the mod_filter directive. Inspect the loaded modules with the appropriate candidate binary or package wrapper before adding the rule. A log and request pair still prove the relevant output more clearly than a successful module report. Inspect the response Content-Encoding, Vary, actual bytes and policy on an unaffected route. To understand caching, identify whether mod_expires, mod_headers, an application or an edge supplies the freshness fields. Two layers can otherwise emit policy that is difficult to reason about.

Apache's LimitRequestBody can constrain request bodies where the directive is supported and correctly scoped. Use byte-sized evidence that matches the actual body sent. If an upstream application handles separately bounded attachments, both sets of requirements remain relevant. For Basic authentication, confirm the necessary authentication and authorization modules and use a scoped provider file readable by the service account. Directives normally name the authentication scheme, realm, provider and applicable authorization requirement. In an actual site keep credential setup inside your approved workflow and verify transport and response outcomes. The snippets on this page do not set up a real login service.

For version details, distinguish Apache's server-wide ServerTokens policy from ServerSignature, which affects signatures on applicable server-generated pages. A proxy can present a different Server header. Use controlled requests to the intended route to verify whether each relevant header and page changed. These observations are enough to say that visible version detail was reduced on a specific response. The independently important tasks of updating the service and enforcing sensible access controls still apply.

Practice, interview questions, quiz and revision cards

Challenge the rollout with an existing old catalog link from a message rather than opening the new home page directly. If its redirect happens to land on a working default page, the real customer journey still failed. Set an expected destination and indicator for correct content. Carry the initial authority and URL through the worksheet and compare them explicitly to the follow-up request. For changes involving a proxy, identify whether it altered the destination header or forwarded the response intact. Those two checks are independent even when a browser presents both results as one navigation.

Use ordinary pressure checks before raising the limit on a real service. Work out the largest acceptable business input along with any form overhead and agreement about responses to larger requests. Decide how the application reports the failure after its own validation, and how a proxy-level 413 looks to the same client. A front limit can protect multiple downstream programs, while each program may have narrower rules for content or per-file dimensions. Predict who should generate the response at below-limit, boundary and above-limit values, then observe it before any actual broad deployment.

For an optimization proposal, write the response body size, selected content type and whether the file was compressible before drawing a conclusion. Use the same file source and compare its decoded response as a control. The percentage from this synthetic fixture would be misleading for a route dominated by images or archives.

Make a four-row acceptance sheet for redirect, cache, compression and upload. Record the positive request, a comparison request whose expected result differs, and the actual response evidence. In the redirect row write the exact destination and the direct catalog marker. In the compression row preserve the identity and compressed file lengths and their decoded equality. In the upload row record the first and rejected sizes and whether the upstream saw each. Explain what each label proved. If you only recorded a browser success or one HTTP status, return to the experiment and collect the missing half.

Why might a user's browser still show an old page after the origin changed?

The browser or another cache may be reusing an eligible stored response. Compare an approved origin check to the normal route and inspect the response's freshness and validation behavior. A cache problem and a wrong deployed file can look alike in a screenshot.

How can you prove gzip preserves what the viewer reads?

Request the same asset with and without the supported coding. Save the raw encoded form, decode it and compare it byte-for-byte with the identity response. Inspect the Content-Encoding and Vary fields as part of the same controlled comparison.

Why can a valid upload be refused before it reaches PHP or another application?

A proxy or front server can enforce its own maximum request body size. Correlate its 413 and request logs with the absence of an upstream entry, using a nearby successful control. The application may also have different POST and per-file limits.

What should you verify on an HTTP-to-HTTPS redirect?

Check the initial status and exact target, then verify the destination's TLS connection, hostname coverage and expected HTTP body. An HTTPS request to an alternate name also needs to establish its initial valid TLS connection.

What does reducing a server's visible version accomplish?

It can limit displayed version information in responses the configured service generates. Check the applicable headers and pages at the public point. Keep software updates and access configuration as separate work.

Quick quiz

  1. Which header describes how the sender encoded this response body?

    1. Content-Encoding
    2. Location
    3. Content-Disposition
    Check the first answer

    A. Content-Encoding can report gzip for the encoded body. Accept-Encoding states the request's preferences, and Vary tells caching software that the request preference matters for response selection.

  2. Which statement describes no-cache?

    1. It always prevents storage of the response
    2. It requires validation before reuse under the applicable cache rules
    3. It applies only to images
    Check the second answer

    B. Storage and reuse are separate. A no-store directive addresses storage. Inspect the actual applied policy for the route.

  3. The large upload returns 413 and produces no upstream count, while the small upload is counted. What does this lab evidence support?

    1. DNS blocked the large request
    2. Compression automatically rejects POST requests
    3. The front limit rejected the large body before forwarding it
    Check the third answer

    C. The tests share a route and method and vary only the body length. The logs show which component received each request.

Redirect evidence

Check the first status and Location separately from the body at the intended destination.

Cache and encoding

Read freshness and validation separately from response encoding. Verify representation changes with the same URL and source bytes.

Upload threshold

Measure the whole submitted body, and trace which hop rejected it before editing limits at every layer.

Credential transport

Basic authentication encodes credentials. Use an approved encrypted connection and keep the password database outside public content.

Primary references