Skip to content
Tutorials Center
My learning

Topics

Lesson 29 of 30 ยท Practice and Review

Interview Questions

Prepare for Nginx and Apache interviews: concepts, nginx vs Apache, location matching, reverse proxying, TLS and troubleshooting scenarios with concise answers.

Interviews about web servers rarely ask you to recite directive names. They test whether you understand what happens to a request, can reason about a configuration you have never seen, and stay calm when something returns a 502. This lesson collects the questions that come up again and again, grouped by topic, with answers short enough to say out loud in a minute or less.

Use it in two ways. Read an answer only after you have tried to give your own, because retrieving an idea teaches far more than recognizing it. And when you can answer, add the why: the best candidates do not stop at "use proxy_pass with a slash", they add "because the URI part replaces the matched prefix". The lessons linked in the answers explain each idea in depth.

Everything in the answers is conceptual or read-only. The two JavaScript examples at the end are stand-ins for self-testing and log triage. They are not nginx or Apache.

What interviewers look for

Mental model Can you trace a request from socket to response?
Trade-offs Nginx or Apache, and why.
Debugging A method, not a guess.
Safety Test, reload, never break production.

Short, structured answers beat long ones.

1 / 2

Concepts

What does a web server do, and why put one in front of an application? It accepts HTTP connections, serves static files directly, and passes dynamic requests to an application over FastCGI, a proxy connection or a module. In front of an app it adds TLS, compression, caching, buffering of slow clients, rate limiting and one stable entry point, so the application only does the work that is really its own. See What a Web Server Does.

What is a reverse proxy, and how is it different from a forward proxy? A forward proxy acts for clients: it sits near them and fetches the internet on their behalf. A reverse proxy acts for servers: clients talk to it as if it were the site, and it chooses a backend. Nginx and Apache are used as reverse proxies for load balancing, TLS termination and caching. See Reverse Proxy Basics.

What is the difference between reload and restart? A reload makes the master process re-read the configuration, start new workers with it and let old workers finish their current requests, so no connection is dropped. A restart stops the process and starts it again, which cuts connections. Always run nginx -t (or apachectl configtest) first, because a failed test means the old configuration keeps running. See Reloads, Zero-Downtime Deploys and Containers.

Nginx versus Apache

How do their architectures differ? Nginx uses a small number of worker processes, each running an event loop that multiplexes thousands of connections. Apache hands connections to workers according to its MPM: prefork uses one process per connection, worker uses threads, and event uses threads plus a listener that parks idle keep-alive connections. Nginx therefore needs far less memory per idle connection, which matters for many slow clients. See Nginx vs Apache.

When would you choose Apache? When you need per-directory configuration with .htaccess (shared hosting, applications that ship their own rules), a module that only exists for Apache, or an existing Apache-based stack your team knows well. It is a fine choice for dynamic sites with PHP-FPM and the event MPM.

When would you choose nginx? For static files, reverse proxying, load balancing, TLS termination and high connection counts. Many production systems run nginx at the edge and an application server (or Apache) behind it.

Why is .htaccess slower, and how do you avoid it? Apache checks every directory along the path of each request for a .htaccess file, and re-reads it each time. Put the same rules in the main configuration inside <Directory> and set AllowOverride None. Nginx has no .htaccess at all, by design. See .htaccess, Directory Rules and AllowOverride.

Configuration and location matching

How does nginx choose a server block? It matches the address and port from listen, then the Host header against server_name in this order: exact name, longest wildcard starting with *., longest wildcard ending with .*, first matching regular expression in file order. If nothing matches, the default_server for that port answers, or the first block if none is marked. See Server Blocks and Choosing a Server.

How does nginx choose a location? First it checks for an exact = match. Otherwise it finds the longest matching prefix; if that prefix uses ^~, it stops there. Else it tests regular expressions (~, ~*) in file order and takes the first match; if none match, it uses the remembered longest prefix. See Location Blocks and Matching Order.

What is the difference between root and alias? root appends the full URI to its path, so location /img/ { root /data; } serves /img/a.png from /data/img/a.png. alias replaces the matched prefix, so location /img/ { alias /data/; } serves it from /data/a.png. With alias, make the slashes of location and alias agree.

What does try_files $uri $uri/ /index.php?$query_string; do? It tests the request as a file, then as a directory, and otherwise makes an internal redirect to /index.php, keeping the query string. It is the front-controller pattern behind clean URLs. See PHP, FastCGI and Application Servers.

What is the difference between return 301 and rewrite ... permanent? Both can redirect, but return is simpler, faster and easier to read, and should be the default. rewrite uses a regular expression and is for cases where you must capture and rebuild the path. See Redirects and Rewrites.

In Apache, in what order are <Directory>, <Files> and <Location> merged? <Directory> (shortest path first) and .htaccess, then regex directory sections, then <Files>, then <Location>, with later ones overriding earlier ones. See Apache httpd Configuration.

Proxying and load balancing

A request to /api/users must reach the backend as /users. How? location /api/ { proxy_pass http://backend/; }. The URI part (the final slash) replaces the matched prefix. Without it the path would be forwarded unchanged.

How does the backend learn the real client IP and scheme? The proxy sets X-Forwarded-For, X-Real-IP and X-Forwarded-Proto, and the application must trust them only when they come from the proxy. Otherwise logs show the proxy's address and redirect logic can loop.

What do you need for WebSockets? proxy_http_version 1.1, plus Upgrade and Connection headers passed through (usually with a map so the header is upgrade only when asked), and a read timeout longer than the default 60 seconds. See WebSockets, Streaming and Long Requests.

Which load-balancing methods does nginx offer, and how does it detect a dead server? Round robin (default, optionally weighted), least_conn, and ip_hash for rough stickiness. Open-source nginx health-checks passively: after max_fails failures within fail_timeout it stops using the server for that period. Active probing requires NGINX Plus or an extra module. See Load Balancing and Health Checks.

TLS

Describe what happens when a browser opens an HTTPS site. After the TCP connection, the client sends a ClientHello with supported versions and ciphers, and the server name (SNI). The server answers with its choice and its certificate chain. The client verifies the chain against trusted roots, checks the name and dates, both sides derive session keys (an ephemeral key exchange), and encrypted traffic starts. TLS 1.3 does this in one round trip. See HTTPS, TLS and Let's Encrypt.

Why does a site work in a browser but fail in curl or on mobile devices? Often the server sends only the leaf certificate and not the intermediates. Browsers sometimes repair that, while other clients cannot. Use fullchain.pem.

What is SNI, and why does it matter? Server Name Indication lets the client name the host inside the handshake, so one IP address can serve many certificates. Without it the server could present only one.

What does HSTS do, and what is its risk? It tells browsers to use HTTPS only for the site for max-age seconds. The risk is that a mistake, such as an expired certificate or a subdomain without HTTPS, cannot be bypassed by users until the time runs out.

Troubleshooting scenarios

You get a 502 Bad Gateway. What do you do? Read the error log first. "Connection refused" means the upstream is not listening: check the service, port or socket path and the proxy_pass address. "Prematurely closed connection" means it crashed mid-request. With PHP-FPM, check pool limits and socket permissions. See Logs and Troubleshooting.

504 versus 502? 502 means the connection to the backend failed or the reply was invalid. 504 means the backend was reachable but did not answer within the timeout. Find the slow work before you raise a timeout.

Static files return 403. Check, in order: the file and every parent directory are readable (and searchable) by the worker's user, the root path is right, there is an index file or autoindex on, no deny rule matches, and on RHEL-family systems SELinux allows the web server to read that path.

Uploads fail with 413. Raise client_max_body_size (default 1 MB) and, for PHP, post_max_size and upload_max_filesize.

A change you made has no effect. You may have edited the wrong file, forgotten to reload, hit a different server block, or been overridden by a more specific location. nginx -T prints the full effective configuration, and apachectl -S shows how vhosts were parsed. Use curl -I -H "Host: example.com" http://127.0.0.1/ to test a specific host.

Test yourself

The first example grades short written answers by looking for key ideas. Edit myAnswers and run it again. It is deliberately crude: it checks for words and cannot judge whether your reasoning is correct, so Question 3 passes although "prefixes, then regex" skips an important rule (the ^~ modifier). A person asking you the same question would notice. The second part is a triage helper that turns log lines into likely causes, which is the habit behind most troubleshooting answers.

JS Stand-in: self-test and log triage

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Notice the last line. A triage tool that says "unknown" honestly is better than one that guesses, and in an interview, "I would read the surrounding log lines and reproduce it with curl" is a stronger answer than a confident wrong one.

The next stand-in asks you to predict, then reveals. It reuses the location rules, so you can check an interview-style question such as "which of these wins?".

JS Stand-in: predict the location

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The surprise is /docs/manual.pdf: the regex beats the /docs/ prefix, but /docs/private/plan.pdf is protected by ^~, so the regex is never consulted. If you predicted both correctly, you understand matching better than many people who have used nginx for years.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A candidate says: 'nginx is faster than Apache because it is written in a faster language'. What is the better explanation?

    The key difference is the concurrency model. Event-driven workers keep memory per idle connection very low, while process-per-connection designs pay for each one.
  2. 2. You reload nginx and the config has a typo. What happens to live traffic?

    A reload parses the new config first. If it is invalid, the running configuration stays active. A restart with a bad config is far more dangerous.
  3. 3. Which answer to 'why does my site work in browsers but fail in curl with a certificate error?' is most likely?

    Browsers may fetch or cache missing intermediates, but curl and many mobile clients will not. Sending the complete chain fixes it.
  4. 4. Which pair describes 502 and 504 correctly?

    502 is a bad gateway answer, usually a refused or broken connection. 504 is a timeout while waiting for a reachable backend.

Summary

  • Answer in the shape what, why, how, and name the directive or command.
  • Nginx is event-driven and light per connection; Apache offers per-directory .htaccess and a rich module set; many systems combine them.
  • Server choice follows name specificity; location choice follows exact, prefix (with ^~), then regex.
  • Proxy answers should mention the trailing slash, forwarded headers, WebSocket headers and timeouts.
  • TLS answers should cover the chain, SNI and the cost of HSTS mistakes.
  • Troubleshoot from the log first: 502 and 504 point in different directions.

Next: Nginx and Apache Cheat Sheet.