Nginx interview questions: config puzzles, reverse proxies and errors

Nginx interview questions test whether you can predict what the server will do with a request: which server block and which location answer it, what proxy_pass sends upstream, and where a 502 or 504 comes from. Expect config-reading puzzles, a reverse proxy or load balancer to write, and a debugging scenario. Strong answers quote the directive and the rule behind it, then say how they would check with nginx -t and the logs.

By Published 8 min read

Where Nginx shows up in interviews

Nginx questions belong to DevOps, SRE, platform, backend and web hosting roles, and appear in some security interviews as the place TLS and rate limits live. The first round is usually concepts: why Nginx handles many connections, what a reverse proxy is for. Then comes config. You may be shown a server block and asked which location serves a URL, or asked to write a proxy with load balancing and WebSocket support. Senior rounds turn into incidents: users see 502s after a deploy, uploads fail, latency doubled behind the proxy. A DevOps engineer loop may cover Nginx in ten minutes; a web platform loop can spend an hour on it.

Architecture and basics

Fundamentals
QuestionWhat it testsWhat a strong answer shows
How does Nginx handle thousands of connections with few processes?ArchitectureOne master process reads config and manages workers. Each worker runs an event loop with non-blocking sockets (epoll on Linux, kqueue on BSD), so one worker juggles many connections instead of one thread per client.
What do worker_processes and worker_connections set?Capacityworker_processes is usually auto, one per CPU core. worker_connections caps open connections per worker, and a proxied request uses two (client and upstream), so the file descriptor limit has to be raised to match.
What happens on nginx -s reload?Zero-downtime changeThe master checks the new config, starts new workers with it and tells old workers to stop accepting connections and exit when their requests finish. A config error keeps the old workers running.
How do you check a config before applying it?Safe changenginx -t tests syntax and file references; nginx -T also prints the full merged config, which helps when includes hide the real settings.
What are contexts?Config structureNested blocks: main, events, http, server, location (plus upstream, map and others). A directive is only valid in some contexts, and many are inherited downward.
Reverse proxy versus forward proxy?VocabularyA reverse proxy sits in front of servers and represents them to clients: TLS termination, load balancing, caching. A forward proxy sits in front of clients and represents them to the internet.
Nginx versus Apache httpd?LandscapeNginx is event-driven and strong at static files and proxying with low memory per connection. Apache's process or thread models and .htaccess files give per-directory flexibility at a cost. Many setups put Nginx in front of application servers.
How is server_name chosen for a request?Virtual hostsAmong blocks listening on the address and port: exact name, then the longest wildcard starting with *, then the longest wildcard ending with *, then the first matching regex. No match goes to the default_server for that listen socket.
Fundamentals. Scroll sideways on a small screen.

Location matching, root, alias and try_files

This is the most common config-reading puzzle. Nginx first checks = exact matches, then finds the longest matching prefix. If that longest prefix has ^~, it stops. Otherwise it tries regex locations (~ case-sensitive, ~* case-insensitive) in the order they appear and uses the first that matches, falling back to the remembered prefix. Work out each request below before reading the answers.

server {
    listen 80;
    location = /health       { return 200 "exact\n"; }
    location ^~ /static/     { return 200 "static prefix\n"; }
    location ~* \.(png|jpg)$ { return 200 "image regex\n"; }
    location /static/img/    { return 200 "longer prefix\n"; }
    location /               { return 200 "fallback\n"; }
}
# Which block answers each request?
#   /health              ?
#   /healthz             ?
#   /static/logo.png     ?
#   /static/img/cat.png  ?
#   /static/img/notes.txt ?
#   /photos/CAT.JPG      ?
Answers: /health is exact; /healthz falls back to /; /static/logo.png is static prefix because ^~ wins as the longest prefix; /static/img/cat.png is image regex, because the longest prefix is /static/img/ (no ^~) so regexes still run; /static/img/notes.txt is longer prefix; /photos/CAT.JPG is image regex since ~* ignores case. Reviewed against the documented rules, not run.
  • root versus alias? root appends the full request URI to the path: location /img/ { root /srv; } serves /srv/img/a.png. alias replaces the matched part: location /img/ { alias /srv/pictures/; } serves /srv/pictures/a.png. Mismatched trailing slashes on alias are a classic source of 404s and path traversal bugs.
  • What does try_files do? It checks files in order and serves the first that exists, otherwise uses the last argument, which can be a URI or =404. try_files $uri $uri/ /index.html is the usual single-page app fallback.
  • How do you capture part of a URL in a regex location? Use named captures such as (?<id>[0-9]+) and refer to them as $id. Named captures stay readable and are not overwritten by a later regex the way numbered ones can be.
  • Why is `if` inside location considered risky? Only return and rewrite inside it behave predictably; other directives can interact in surprising ways. Prefer map, try_files and separate locations.
  • What does return 301 versus rewrite do? return ends processing and sends the status and URL, which is the clearest way to redirect. rewrite changes the URI with a regex and can loop through location matching again.

Reverse proxying and load balancing

Intermediate questions
QuestionWhat it testsWhat a strong answer shows
What changes when proxy_pass has a trailing slash?URI handlingWithout a URI part (proxy_pass http://app;) the original request URI is passed unchanged. With one (proxy_pass http://app/;) the part matching the location prefix is replaced, so /api/users in location /api/ becomes /users upstream.
Which headers should a proxy set?Client identityHost, X-Real-IP, X-Forwarded-For using $proxy_add_x_forwarded_for, and X-Forwarded-Proto, so the app sees the real host, client and scheme. The app should trust these only from known proxies.
Why did headers set in the server block disappear in one location?Inheritanceproxy_set_header and add_header are inherited only if the current level defines none. One add_header in a location drops every header set above it, a common way security headers vanish.
Which load-balancing methods exist?UpstreamsRound robin by default (with weights), least_conn, ip_hash for sticky clients, hash on any key with consistent for ketama-style hashing, and random. backup servers take traffic only when the others are down.
How does open-source Nginx detect a dead backend?Health checksPassively: after max_fails failed attempts within fail_timeout, the server is skipped for fail_timeout. Active health checks that probe a URL are a commercial NGINX Plus feature, so open-source setups rely on passive checks or an outside tool.
How do you keep connections to upstreams open?Performancekeepalive in the upstream block, plus proxy_http_version 1.1 and an empty Connection header in the location. Without them Nginx opens a new connection per request, which adds latency and can exhaust ports.
How do you proxy WebSockets?Protocol upgradeHTTP/1.1 to the upstream, pass the Upgrade header and set Connection to upgrade (usually through a map), and raise proxy_read_timeout so idle sockets are not cut after the default 60 seconds.
What does proxy_next_upstream control?RetriesWhich failures (error, timeout, certain status codes) make Nginx retry the request on another server. Retrying non-idempotent requests such as POST is off by default for good reason.
Intermediate questions. Scroll sideways on a small screen.
upstream app_backend {
    least_conn;
    server 10.0.1.11:8080 max_fails=3 fail_timeout=10s;
    server 10.0.1.12:8080 max_fails=3 fail_timeout=10s;
    server 10.0.1.13:8080 backup;
    keepalive 32;                      # idle connections kept open to the upstreams
}

limit_req_zone $binary_remote_addr zone=per_ip:10m rate=10r/s;

map $http_upgrade $connection_upgrade {
    default upgrade;
    ''      close;
}

server {
    listen 80;
    server_name app.example.com;
    return 301 https://$host$request_uri;
}

server {
    listen 443 ssl;
    http2 on;                          # nginx 1.25.1+; older versions use "listen 443 ssl http2"
    server_name app.example.com;

    ssl_certificate     /etc/nginx/tls/app.example.com.crt;
    ssl_certificate_key /etc/nginx/tls/app.example.com.key;
    ssl_protocols       TLSv1.2 TLSv1.3;

    client_max_body_size 20m;

    location /api/ {
        limit_req zone=per_ip burst=20 nodelay;
        proxy_pass http://app_backend;
        proxy_http_version 1.1;
        proxy_set_header Connection "";          # needed for upstream keepalive
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_read_timeout 30s;
    }

    location /ws/ {
        proxy_pass http://app_backend;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection $connection_upgrade;
        proxy_set_header Host $host;
        proxy_read_timeout 1h;
    }

    location / {
        root /var/www/app;
        try_files $uri $uri/ /index.html;    # single-page app fallback
    }
}
A reverse proxy many interviews ask for: HTTP to HTTPS redirect, TLS, an upstream with least_conn, passive health settings and keepalive, a per-IP rate limit on the API, WebSocket support and a single-page app fallback. Reviewed by hand, not run. The `http2 on;` directive needs nginx 1.25.1 or later.

Caching, rate limiting, TLS and logs

  • How does proxy caching work? proxy_cache_path defines the disk location and a shared memory zone for keys; proxy_cache enables it in a location, proxy_cache_valid sets lifetimes per status, and the cache key defaults to scheme, host and URI. Adding $upstream_cache_status to a response header shows HIT, MISS or STALE while testing.
  • What do proxy_cache_use_stale and proxy_cache_lock do? The first serves an expired copy when the upstream errors or while a refresh runs. The second lets only one request fetch a missing item while others wait, which stops a stampede on a cold key.
  • How does limit_req work? A leaky bucket per key, often $binary_remote_addr, at a set rate. burst allows a queue of extra requests; nodelay serves the burst at once instead of spacing it out. Excess requests get 503 by default, which limit_req_status can change to 429.
  • limit_req versus limit_conn? limit_req caps request rate; limit_conn caps simultaneous connections per key, useful for downloads.
  • How do you harden TLS? Allow TLS 1.2 and 1.3 only, use certificates with the full chain, enable OCSP stapling where it applies, add HSTS once HTTPS is stable everywhere, and set ssl_session_cache to reuse handshakes.
  • How did enabling HTTP/2 change in recent versions? Older configs add http2 to the listen line. From nginx 1.25.1 a separate http2 on; directive is used and the listen parameter is deprecated. HTTP/3 needs a quic listen and a build with QUIC support.
  • Which variables would you add to the access log for latency work? $request_time (total time Nginx spent), $upstream_response_time and $upstream_connect_time. Comparing them tells you whether the slowness is in the app, the network or the client.
  • What does server_tokens off do? Removes the version number from error pages and the Server header. It hides a detail, nothing more, so patching still matters.

Troubleshooting scenarios

Debugging and design scenarios
QuestionWhat it testsWhat a strong answer shows
Users see 502 Bad Gateway after a deploy.Upstream errorsRead error.log: connection refused means the app is down or on another port; "upstream prematurely closed" means it crashed mid-request; permission denied on a Unix socket means the socket owner changed. Check the app before touching Nginx.
Some requests return 504 Gateway Timeout.TimeoutsThe upstream accepted but answered later than proxy_read_timeout. Find the slow endpoint with $upstream_response_time in the log. Raising the timeout hides the problem; moving long jobs to a queue fixes it.
Uploads over 1 MB fail with 413.Limitsclient_max_body_size defaults to 1m. Raise it in the right server or location, and check limits in any proxy or load balancer in front.
The access log is full of status 499.Client behavior499 is Nginx's code for a client that closed the connection before the response. Often a client or load balancer timeout shorter than the backend's response time.
The app builds redirects to http:// although users are on HTTPS.Forwarded schemeTLS ends at Nginx and the app sees plain HTTP. Pass X-Forwarded-Proto and configure the framework to trust it from the proxy.
Design an edge layer for an API that needs per-customer limits and canary releases.Designlimit_req keyed by an API key via map, a split_clients or weighted upstream for a small canary share, separate upstream pools, structured logs with request IDs, and alerting on the 5xx rate per upstream.
Debugging and design scenarios. Scroll sideways on a small screen.

Fictional example

Answering "We added a CSP header and now HSTS is gone. Why?"
Interviewer
HSTS and X-Frame-Options are set in the server block. Someone added a Content-Security-Policy header inside location /app/, and now pages under /app/ have only the CSP header. What happened?
Candidate
That is add_header inheritance. A location inherits add_header directives from the server block only if it defines none of its own. Once /app/ has one add_header, it drops all the inherited ones, so HSTS and X-Frame-Options are gone for that path. I would confirm with curl -I on a URL under /app/ and compare it with the root. The fix is either to repeat the shared headers in that location or, cleaner, to move them into an include file that every location pulls in. I would also check whether our nginx version offers a newer way to control this inheritance before choosing. Then I would add a test in CI that checks the security headers on a few key paths so this cannot slip again.

How to prepare for Nginx interview questions

  1. Run it locallyStart Nginx in a container with a tiny app behind it, then change config and reload. Watch error.log while you break things on purpose: stop the app, slow it down, send a large upload.
  2. Drill location matchingWrite ten locations and twenty URLs, predict the winner for each, then check with a return directive that names the block. Include ^~, regex order and nested prefixes.
  3. Build the standard proxy from memoryRedirect, TLS, upstream with keepalive, forwarded headers, WebSockets and a rate limit. Explain every line out loud as if in the interview.
  4. Learn the status codesReproduce 413, 499, 502 and 504 and read the matching error.log lines until you can name the cause from the message.
  5. Know the neighborsBe ready to compare Nginx with HAProxy, a cloud load balancer and a Kubernetes ingress controller, and to say where TLS should end.

Nginx sits between the network and the app. For queues behind the proxy see RabbitMQ interview questions, for the scripts that deploy and reload it see shell scripting interview questions, and for the design side see the rate limiter and caching guides.

Config puzzles reward thinking out loud in the right order. Natively, an AI interview assistant for Mac and Windows, keeps a transcript of a practice round, can read a server block or an error.log excerpt from a screenshot and offers a suggested answer next to yours as you reason through it. Pro or the free trial lets it use your résumé and the job description, and the transcript and notes of each mock are saved so you can see where your explanation drifted.

Questions people ask

What are common Nginx interview questions?

How the master and worker processes handle many connections, how a location is chosen, root versus alias, what a trailing slash on proxy_pass does, which load-balancing methods exist, how to proxy WebSockets, and how to debug 502 and 504 errors.

How does Nginx choose a location block?

It checks exact = matches first, then remembers the longest matching prefix. If that prefix has ^~ it is used; otherwise regex locations are tried in file order and the first match wins, with the prefix as the fallback.

What is the difference between a 502 and a 504 in Nginx?

A 502 means the upstream refused, closed or broke the connection. A 504 means it accepted the request but did not answer within the proxy timeout.

Why does a header disappear when I add add_header in a location?

add_header is inherited from outer blocks only when the current block defines none. Adding one in a location drops the inherited headers, so repeat them or use a shared include.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP