🚀 Ready to Land Your Dream Infrastructure Job? Visit Our Job Interview Portal!
500+ Cloud, Web Server & Programming Interview Questions | Mock Tests | AI-Powered Prep
🔗 Go to Job Interview Portal – Start Preparing Now!📑 Table of Contents
🌱 BEGINNER LEVEL
0–2 Years Experience – 60 Q&As
Core Nginx concepts, installation, basic configuration, virtual hosts, and logging.
Q1
📖 STORY You join a startup. The CTO asks, "Why did we choose Nginx over Apache?" How do you explain?
Answer: Nginx (pronounced "engine-x") is a high‑performance, event‑driven web server and reverse proxy. Unlike Apache's process‑per‑connection model, Nginx uses an asynchronous, non‑blocking architecture that handles thousands of concurrent connections with low memory. It excels at serving static files, acting as a reverse proxy, and load balancing. We chose it for speed, scalability, and efficient resource usage.
💡 "Nginx is like a lightning‑fast traffic controller – it handles massive traffic without breaking a sweat."
Q2
How do you install Nginx on Ubuntu/CentOS?
Answer: Ubuntu: `sudo apt update && sudo apt install nginx`. CentOS/RHEL: `sudo yum install epel-release && sudo yum install nginx`. Start with `sudo systemctl start nginx`. Main configuration is in `/etc/nginx/nginx.conf`.
Q3
What is the master process and worker processes in Nginx?
Answer: Nginx runs one master process (as root) that reads configuration and manages worker processes. The worker processes (as a non‑privileged user, e.g., `www-data`) handle client connections. The master process never handles requests itself; it only controls workers. This architecture enhances stability and security.
Q4
What is the default port Nginx listens on? How to change it?
Answer: Port 80 for HTTP, 443 for HTTPS. Change with the `listen` directive inside a `server` block: `listen 8080;`. You can also listen on a specific IP: `listen 192.168.1.10:80;`.
Q5
What is a server block (virtual host) in Nginx?
Answer: A `server` block is equivalent to Apache's virtual host. It allows one Nginx instance to serve multiple websites. Example: `server { listen 80; server_name example.com; root /var/www/example; }`. Nginx selects the server block based on the `Host` header.
Q6
Explain the `location` directive and its matching order.
Answer: `location` blocks define how to process requests for specific URIs. Matching order (priority): 1. Exact match (`= /exact`) 2. Preferential prefix with `^~` 3. Regex matches (`~` case‑sensitive, `~*` case‑insensitive) 4. Plain prefix match (longest wins). Exact match has highest priority; if multiple regex, first defined wins.
Q7
How do you restart Nginx gracefully?
Answer: `sudo systemctl reload nginx` or `sudo nginx -s reload`. This tests the configuration and applies changes without dropping active connections. `sudo nginx -s reopen` reopens log files.
Q8
What is the syntax for a basic reverse proxy in Nginx?
Answer: Use the `proxy_pass` directive inside a `location` block: `location / { proxy_pass http://backend-server:8080; }`. Additional headers like `proxy_set_header Host $host;` and `proxy_set_header X-Real-IP $remote_addr;` are common.
Q9
What is `try_files` and how is it used?
Answer: `try_files` checks for the existence of files in order and serves the first found. Example: `try_files $uri $uri/ /index.html;`. If none exist, it can redirect to a fallback. It's essential for single‑page applications and PHP front controllers.
Q10
How do you enable PHP support with Nginx? (PHP‑FPM)
Answer: Nginx doesn't embed PHP. Use `fastcgi_pass` to pass PHP requests to a PHP‑FPM socket. Example: `location ~ \.php$ { include fastcgi_params; fastcgi_pass unix:/run/php/php8.0-fpm.sock; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; }`.
Q11
How do you test Nginx configuration syntax?
Answer: Run `sudo nginx -t`. It checks the syntax of all config files and reports errors. Always run before reloading.
Q12
What are Nginx access and error logs? Where are they stored?
Answer: Access log (`/var/log/nginx/access.log` by default) records every request. Error log (`/var/log/nginx/error.log`) records errors. Log paths are set with `access_log` and `error_log` directives.
Q13
What is the difference between `root` and `alias`?
Answer: `root` appends the URI to the specified path. `alias` replaces the matched location part. Example: `location /images/ { alias /data/uploads/; }` – a request to `/images/photo.jpg` maps to `/data/uploads/photo.jpg`, not `/data/uploads/images/photo.jpg`.
Q14
How do you set up a simple static file server with directory listing?
Answer: Inside a `server` block: `location / { root /var/www/files; autoindex on; }`. `autoindex on` enables directory listing.
Q15
What is the `worker_processes` directive? How to set it?
Answer: Defines how many worker processes to spawn. Best practice is `worker_processes auto;` which sets it to the number of CPU cores. This optimizes concurrency.
Q16
How do you redirect HTTP to HTTPS in Nginx?
Answer: Create a server block for port 80: `server { listen 80; server_name example.com; return 301 https://$host$request_uri; }`. This is a permanent redirect.
Q17
Explain `sendfile` and `tcp_nopush`.
Answer: `sendfile on;` enables the kernel to send files directly from disk to socket, bypassing user space. `tcp_nopush on;` optimizes sending of headers and file together. Both improve static file performance.
Q18
What is `gzip` compression in Nginx? How to enable?
Answer: `gzip on;` enables compression. Use `gzip_types text/plain text/css application/json application/javascript text/xml;` to specify MIME types. `gzip_min_length 1000;` avoids compressing small files. Reduces bandwidth significantly.
Q19
How do you set custom error pages (e.g., 404, 502)?
Answer: Use `error_page` directive: `error_page 404 /custom_404.html;` or `error_page 500 502 503 504 /50x.html;`. The URI is relative to `root` or can be a named location.
Q20
What does the `include` directive do?
Answer: It includes another configuration file. For example, `include /etc/nginx/conf.d/*.conf;` loads all `.conf` files from that directory. This keeps configuration modular and clean.
Q21
What is the default user Nginx runs as? Why?
Answer: Usually `www-data` (Debian) or `nginx`. It's set with `user` directive in the main context. Running as a non‑root user limits potential damage from a security breach. Only the master process runs as root.
Q22
How do you view the currently loaded Nginx modules?
Answer: Run `nginx -V 2>&1 | grep --color -o '\-\-with-\S*'` to see compiled‑in modules. For dynamic modules, they are loaded with `load_module` directives.
Q23
What is a `map` directive? Give a simple example.
Answer: `map` creates a new variable based on another variable. Example: `map $http_user_agent $mobile { default 0; "~*Mobile" 1; }`. Then you can use `$mobile` in `if` or other directives.
Q24
How do you deny access to a specific IP or range?
Answer: Use `deny` and `allow` inside a `location` block: `deny 192.168.1.100; allow 192.168.1.0/24; deny all;`. Rules are evaluated sequentially.
Q25
What does `server_name _` mean?
Answer: It's a catch‑all server block that matches any hostname not matched by other server blocks. Often used to drop invalid requests: `return 444;` (Nginx‑specific non‑standard code that closes connection).
Q26
How do you set up basic HTTP authentication in Nginx?
Answer: Use `auth_basic` and `auth_basic_user_file`. Create a password file with `htpasswd -c /etc/nginx/.htpasswd user1`. Then: `location /private { auth_basic "Restricted"; auth_basic_user_file /etc/nginx/.htpasswd; }`.
Q27
What is the difference between `return` and `rewrite`?
Answer: `return` is simpler and faster for simple redirects (e.g., `return 301 https://example.com;`). `rewrite` uses regular expressions and can perform complex URL transformations, but is slightly more resource‑intensive. Prefer `return` when possible.
Q28
What is a named location (`@name`)? When is it used?
Answer: A named location is a `location` that is not used for direct requests but can be referenced by directives like `try_files` or `error_page`. Example: `location @fallback { proxy_pass http://backend; }` and `try_files $uri @fallback;`.
Q29
How do you configure Nginx to serve pre‑compressed files (gzip_static)?
Answer: Enable `gzip_static on;`. Nginx will look for `.gz` versions of files (e.g., `style.css.gz`) and serve them instead of compressing on‑the‑fly. Requires `ngx_http_gzip_static_module`.
Q30
How do you log to syslog instead of files?
Answer: Use `access_log syslog:server=unix:/dev/log facility=local1;` and `error_log syslog:server=unix:/dev/log;`. Requires the `--with-syslog` module.
Q31
What is `client_max_body_size`?
Answer: Sets the maximum allowed size of the client request body. Default is 1MB. To allow larger file uploads, set `client_max_body_size 20M;`. If exceeded, Nginx returns 413 (Request Entity Too Large).
Q32
How do you set up a simple load balancer with Nginx?
Answer: Define an upstream group: `upstream backend { server backend1.example.com; server backend2.example.com; }`. Then use `proxy_pass http://backend;`. Default algorithm is round‑robin.
Q33
What are the common HTTP status codes 200, 301, 404, 502 in Nginx context?
Answer: 200 OK, 301 Moved Permanently (redirect), 404 Not Found, 502 Bad Gateway (upstream server returned invalid response or is down). Understanding these helps in log analysis and troubleshooting.
Q34
How do you set up a wildcard server block?
Answer: Use `server_name *.example.com;` or `server_name ~^(www\.)?(.+)$;` with regex. You can capture the subdomain and use it to set the root dynamically.
Q35
How do you block a specific user‑agent?
Answer: Use `if ($http_user_agent ~* "BadBot") { return 403; }` inside a server or location block. Or use `map` for cleaner approach.
Q36
What is `keepalive_timeout`?
Answer: The time (in seconds) a keep‑alive connection stays open waiting for the next request. Default is 75s. Reducing it (e.g., 15s) can free up resources on high‑traffic sites.
Q37
How do you reload Nginx config without downtime?
Answer: `sudo nginx -s reload` or `sudo systemctl reload nginx`. It sends a signal to the master process to reload config and gracefully restart workers.
Q38
What is the purpose of `server_tokens off;`?
Answer: It hides the Nginx version number from error pages and the `Server` response header, improving security by obscurity. Set in `http` or `server` context.
Q39
How do you serve a simple "Hello World" page with Nginx?
Answer: Create an `index.html` with "Hello World". Set `root` to the directory containing it. Or use `return 200 "Hello World"; add_header Content-Type text/plain;` in a location block.
Q40
As a beginner, how would you confidently answer "Tell me about your Nginx experience"?
🎤 "I've installed and configured Nginx on Linux, set up virtual hosts, configured SSL, used reverse proxy for Node.js apps, and tuned basic performance settings like gzip and worker_processes. I regularly analyze access and error logs, and test config with `nginx -t`. I'm now exploring load balancing and caching."
Q41
What is the difference between `proxy_pass` with and without trailing slash?
Answer: `proxy_pass http://backend/;` with trailing slash replaces the matched location path. Without trailing slash, it appends the full URI to the backend. Example: `location /app/ { proxy_pass http://backend/; }` – `/app/foo` goes to `http://backend/foo`. Without slash, it goes to `http://backend/app/foo`.
Q42
How do you enable directory listing only for a specific path?
Answer: `location /downloads/ { root /var/www; autoindex on; }`. Ensure proper permissions.
Q43
What is `default_type` directive?
Answer: Sets the default MIME type for responses. Usually `default_type application/octet-stream;`. It's used when Nginx can't determine the type from the file extension.
Q44
How do you rotate Nginx logs?
Answer: Use `logrotate` with a config file in `/etc/logrotate.d/nginx`. It can compress and rotate logs daily/weekly. Nginx also supports `nginx -s reopen` to reopen logs after rotation.
Q45
What does `worker_connections` specify?
Answer: The maximum number of simultaneous connections a single worker process can handle. Total connections = `worker_processes * worker_connections`. Default is 1024. Increase for high‑traffic sites.
Q46
How do you set custom headers in Nginx responses?
Answer: `add_header X-Custom "value";` in `http`, `server`, or `location` context. `add_header` replaces inherited headers; to add without replacing, use `add_header` with `always`? In newer versions, `add_header` behaves like setting unless `always` is used; careful with inheritance.
Q47
What is the `events` block? What is configured there?
Answer: It defines connection processing settings. Example: `events { worker_connections 1024; use epoll; }`. `use epoll` is the efficient event‑processing method on Linux.
Q48
How do you block access to hidden files (like `.htaccess`, `.env`)?
Answer: `location ~ /\. { deny all; return 404; }`. This blocks any request starting with a dot.
Q49
What is `try_files` used for in a Single Page Application (SPA)?
Answer: `location / { try_files $uri $uri/ /index.html; }`. If a file or directory doesn't exist, it serves `index.html`, allowing client‑side routing to handle the path.
Q50
How do you check Nginx version and compile flags?
Answer: `nginx -V` shows version, configure arguments, and included modules. `nginx -v` shows only version.
Q51
What is the `ssl_certificate` and `ssl_certificate_key` directives?
Answer: Used in a server block listening on 443 to specify the path to the SSL certificate and private key. Example: `ssl_certificate /etc/nginx/ssl/cert.pem; ssl_certificate_key /etc/nginx/ssl/key.pem;`.
Q52
How do you redirect a specific page to a new URL?
Answer: `location = /old-page { return 301 /new-page; }` or using `rewrite ^/old-page$ /new-page permanent;`.
Q53
What is the meaning of `$host` vs `$http_host`?
Answer: `$host` is the hostname from the request line or `Host` header, normalized (lowercase, no port). `$http_host` is the exact `Host` header. Use `$host` for most cases; it's safer against certain attacks.
Q54
How do you set up Nginx as a mail proxy?
Answer: Nginx has a mail module (`ngx_mail`). Configure with `mail` block and `server` directives for SMTP, IMAP, POP3. It's not covered in detail here, but is a feature for load balancing mail servers.
Q55
How do you stop Nginx?
Answer: `sudo systemctl stop nginx` or `sudo nginx -s quit` (graceful) / `sudo nginx -s stop` (fast).
Q56
What is a `fastcgi_cache` and how to enable it?
Answer: It caches responses from PHP‑FPM or other FastCGI backends. Define a cache path: `fastcgi_cache_path /var/cache/nginx levels=1:2 keys_zone=phpcache:10m;`. Then in location: `fastcgi_cache phpcache; fastcgi_cache_valid 200 10m;`.
Q57
How do you handle the "nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)" error?
Answer: Another process is listening on port 80. Find with `sudo netstat -tulpn | grep :80`. Stop that process or change the Nginx listen port.
Q58
What does `include /etc/nginx/mime.types;` do?
Answer: It loads the MIME type definitions so Nginx can set the `Content-Type` header based on file extensions. It's essential for proper file serving.
Q59
How do you set the charset to UTF-8?
Answer: `charset utf-8;` in `http`, `server`, or `location` context. Adds `Content-Type` header with charset.
Q60
🤖 AI How is AI influencing Nginx management?
Answer: AI tools help generate config snippets, detect anomalies in logs (e.g., ML‑based WAF), and predict traffic patterns for auto‑scaling. Nginx's role as an API gateway also benefits from AI‑driven traffic routing. But human expertise remains vital for tuning.
🔥 INTERMEDIATE LEVEL
2–5 Years Experience – 60 Q&As
Advanced location matching, rewrite, proxy, load balancing, SSL/TLS, caching, and performance tuning.
Q61
📖 You're optimizing Nginx for a high‑traffic news site. What key settings do you adjust?
Answer: Set `worker_processes auto;`, `worker_connections 4096;`, `multi_accept on;`, `sendfile on;`, `tcp_nopush on;`, `keepalive_timeout 15;`, `gzip on;` with proper types. Increase `worker_rlimit_nofile`. Use `open_file_cache` for file descriptors. Ensure PHP‑FPM uses a socket with `fastcgi_cache`. Monitor with stub_status for tuning.
Q62
Explain the `rewrite` directive with flags (`last`, `break`, `redirect`, `permanent`).
Answer: `rewrite regex replacement [flag];`. `last` – stops processing current `rewrite` directives but searches for a new location. `break` – stops rewriting and continues request processing in current location. `redirect` – temporary 302 redirect. `permanent` – 301 permanent redirect.
Q63
How does Nginx load balancing work? Describe algorithms.
Answer: Default round‑robin. Others: `least_conn` (least active connections), `ip_hash` (sticky sessions based on client IP), `hash` (custom key), `random` with `two` (select two randomly, pick least conn). Example: `upstream backend { least_conn; server s1; server s2; }`.
Q64
How do you handle WebSocket proxying in Nginx?
Answer: Set headers: `proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade";`. Use `proxy_pass http://backend;`. Also increase `proxy_read_timeout` to prevent timeout during idle WebSocket connections.
Q65
What is the `stub_status` module and how to enable it?
Answer: Provides basic metrics (active connections, requests). Enable: `location /nginx_status { stub_status; allow 127.0.0.1; deny all; }`. Requires `ngx_http_stub_status_module`.
Q66
How do you implement caching for proxy responses?
Answer: Define `proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=mycache:10m;`. Then in location: `proxy_cache mycache; proxy_cache_valid 200 302 10m; proxy_cache_valid 404 1m;`. Add `proxy_cache_key` for custom cache keys.
Q67
How to set up SSL with modern security (TLS 1.2/1.3, strong ciphers)?
Answer: `ssl_protocols TLSv1.2 TLSv1.3; ssl_ciphers 'ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384'; ssl_prefer_server_ciphers on;`. Also enable `ssl_session_cache shared:SSL:10m;` and `ssl_stapling on;` for OCSP stapling.
Q68
How do you rate limit requests with Nginx?
Answer: Use `limit_req_zone` to define a zone (e.g., `limit_req_zone $binary_remote_addr zone=one:10m rate=10r/s;`). Then in location: `limit_req zone=one burst=20 nodelay;`. `burst` allows bursts; `nodelay` processes immediately.
Q69
What is the difference between `proxy_buffer` and `proxy_buffers`?
Answer: `proxy_buffer` sets the buffer size for the first part of the response. `proxy_buffers` sets the number and size of buffers for the rest. Tuning these prevents upstream response being written to disk.
Q70
How to configure health checks for upstream servers?
Answer: Nginx Plus has active health checks. In OSS, use passive checks with `max_fails` and `fail_timeout` in the upstream server definition: `server backend1 max_fails=3 fail_timeout=30s;`. Nginx will mark it down if it fails 3 times in 30s.
Q71
How do you implement sticky sessions without Nginx Plus?
Answer: Use `ip_hash` in upstream, or cookie‑based stickiness with the `sticky` directive (only in Plus). For OSS, you can use `map` with a custom cookie and `hash` directive, or rely on application‑level session handling.
Q72
What is `proxy_next_upstream`?
Answer: Defines conditions under which a request should be passed to the next upstream server (e.g., error, timeout, invalid_header). Example: `proxy_next_upstream error timeout http_502;`. Prevents immediate failure if a backend is temporarily unhealthy.
Q73
Explain `open_file_cache` and its benefits.
Answer: Caches metadata about open files (e.g., existence, permissions). Reduces filesystem I/O. Example: `open_file_cache max=1000 inactive=20s; open_file_cache_valid 30s; open_file_cache_min_uses 2;`.
Q74
How to set up Nginx as a TCP/UDP load balancer (stream module)?
Answer: Use `stream` block outside `http`. Example: `stream { upstream mysql { server db1:3306; server db2:3306; } server { listen 3306; proxy_pass mysql; } }`. Requires `--with-stream` module.
Q75
What is `ngx_http_limit_conn_module`?
Answer: Limits connections per defined key (e.g., IP). `limit_conn_zone $binary_remote_addr zone=addr:10m;` then `limit_conn addr 10;` in location. Prevents one IP from opening too many connections.
Q76
How do you configure Nginx to serve large files efficiently (e.g., video)?
Answer: Use `sendfile on;`, `tcp_nopush on;`, and for range requests ensure `proxy_cache` or direct file serving. Also `output_buffers` and `aio` directive with `directio` for asynchronous I/O on Linux (e.g., `aio threads; directio 5m;`).
Q77
How to debug a 502 Bad Gateway error with Nginx?
Answer: Check that the upstream server is running and reachable. Look at Nginx error log (`/var/log/nginx/error.log`). Verify `proxy_pass` URL, firewall rules, and upstream `max_fails`. If using Unix socket, check permissions.
Q78
What is `server_names_hash_bucket_size`?
Answer: Adjusts the hash table size for server names. Increase if you have many long server names. Set in `http` context: `server_names_hash_bucket_size 64;`.
Q79
How to set up a maintenance page that returns 503 for all requests except a specific IP?
Answer: Use `if ($remote_addr != "192.168.1.100") { return 503; }` and `error_page 503 /maintenance.html;`. Better: use a map and `if` with `return`.
Q80
As an intermediate, how would you answer "Describe a complex Nginx issue you solved"?
🎤 "We had intermittent 504s from an upstream API. I discovered `proxy_read_timeout` was too low for some slow requests. I increased it and also set `proxy_next_upstream timeout;` to retry. I added `proxy_cache` for get requests to reduce load. Monitored with stub_status and saw connection spikes, so I increased `worker_connections`. Problem resolved."
Q81
How to configure Nginx for HTTP/2?
Answer: `listen 443 ssl http2;`. Ensure SSL is configured, because browsers only support HTTP/2 over TLS. Also consider `http2_push` (though now deprecated in some browsers) and `http2_max_concurrent_streams`.
Q82
What is the `ssl_trusted_certificate` directive used for?
Answer: Specifies a file with trusted CA certificates for verifying client certificates (`ssl_client_certificate`) or for OCSP stapling. Used in two‑way SSL authentication.
Q83
How do you set up mutual TLS (mTLS) in Nginx?
Answer: `ssl_client_certificate /path/ca.pem; ssl_verify_client on;`. Nginx will request and validate client certificate against the specified CA. Can be optional with `optional`.
Q84
Explain the `map` directive for caching based on URI.
Answer: `map $uri $cacheable { default 1; ~*\.(jpg|png|css|js)$ 0; }`. Then use `proxy_cache_bypass $cacheable;` to skip cache for static assets. Great for granular caching control.
Q85
What are `proxy_cache_lock` and `proxy_cache_lock_timeout`?
Answer: When multiple requests for the same uncached resource arrive, only one is allowed to fetch from upstream, others wait. `proxy_cache_lock on;` enables this, preventing cache stampede. Timeout sets how long they wait before fetching themselves.
Q86
How to strip a prefix from a URL before proxying?
Answer: Use `proxy_pass` with trailing slash: `location /api/ { proxy_pass http://backend/; }`. Nginx automatically removes `/api/`. Or use `rewrite ^/api/(.*) /$1 break;` then `proxy_pass http://backend;`.
Q87
What is the `resolver` directive? When is it needed?
Answer: Specifies DNS servers for Nginx to resolve upstream names defined as domain names (instead of IPs). Required when using variables in `proxy_pass` or with `upstream` with `resolve` parameter. Example: `resolver 8.8.8.8 valid=30s;`.
Q88
How to dynamically configure upstream servers without reloading?
Answer: Nginx Plus has dynamic reconfiguration API. For OSS, you can use `include` with a file containing upstream servers, modify the file, then reload or use `nginx -s reload`. Some use DNS with `resolve` to change backends.
Q89
What is the difference between `rewrite` and `proxy_redirect`?
Answer: `rewrite` changes the request URI before processing. `proxy_redirect` modifies `Location` and `Refresh` headers in the upstream response to match the proxy’s URL, useful when the backend redirects to an internal URL.
Q90
How do you limit the request rate to a specific location?
Answer: `limit_req_zone $binary_remote_addr zone=mylimit:10m rate=5r/s;` then in location: `limit_req zone=mylimit burst=10;`. Combine with `limit_req_status 429;` to return a custom code.
Q91
How to configure Nginx to pass client IP to backend correctly when using a CDN?
Answer: Use `set_real_ip_from` for CDN IP ranges, then `real_ip_header X-Forwarded-For;`. This replaces `$remote_addr` with the real client IP from the header. Requires `ngx_http_realip_module`.
Q92
What is `ngx_http_sub_module`?
Answer: Allows substitution of text in the response body. Example: `sub_filter 'http://internal' 'https://public'; sub_filter_once off;`. Used for fixing links in proxied content.
Q93
How to handle CORS headers in Nginx?
Answer: `if ($request_method = 'OPTIONS') { add_header 'Access-Control-Allow-Origin' '*'; add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS'; add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range'; return 204; }`. For non‑OPTIONS, add the allow‑origin header.
Q94
What are the benefits of `aio` and `directio`?
Answer: `aio` enables asynchronous I/O, offloading read/write to a thread pool. `directio` bypasses the page cache for large files, reducing memory usage. Use `aio threads; directio 5m;` for serving large media files efficiently.
Q95
How to implement a request ID for tracing?
Answer: Use `$request_id` variable (Nginx 1.11.0+) which is a unique UUID. Log it and pass it to upstream: `proxy_set_header X-Request-Id $request_id;`. Enables end‑to‑end request tracing.
Q96
What is the difference between `proxy_buffering on` and `off`?
Answer: When on, Nginx buffers the upstream response before sending to client. When off, it sends synchronously (useful for streaming). Off disables buffering but can cause blocking if client is slow.
Q97
How to monitor Nginx metrics with Prometheus?
Answer: Use `nginx-prometheus-exporter` or `nginx-module-vts`. The exporter scrapes the stub_status page and exposes metrics. Then Prometheus collects and Grafana visualizes.
Q98
What is `ngx_http_slice_module`?
Answer: Splits a request into byte‑range subrequests, fetches them from upstream, and assembles the response. Useful for delivering large files through a reverse proxy with caching. Requires `slice` directive.
Q99
How to set up Nginx with Let's Encrypt automatically?
Answer: Use Certbot with Nginx plugin: `sudo certbot --nginx -d example.com`. Certbot edits the Nginx config, obtains the certificate, and sets up auto‑renewal. Renewal hooks reload Nginx.
Q100
How to block specific countries using GeoIP?
Answer: Use `ngx_http_geoip_module` with MaxMind database. Example: `geoip_country /etc/nginx/GeoIP.dat; map $geoip_country_code $allowed { default yes; CN no; }` then `if ($allowed = no) { return 403; }`.
Q101
What is the `split_clients` directive?
Answer: Creates A/B testing or canary deployments by hashing a variable and assigning to a group. Example: `split_clients "${remote_addr}AAA" $variant { 50% backend1; 50% backend2; }` then `proxy_pass http://$variant;`.
Q102
How to set up Nginx as an API gateway?
Answer: Use multiple `location` blocks for different services, apply authentication (JWT validation via `ngx_http_auth_jwt_module` or Lua), rate limiting, caching. Route based on path or host. Nginx Plus has native API gateway features; OSS can do it with additional modules.
Q103
What is the `ngx_stream_ssl_preread_module`?
Answer: Allows extracting information from the ClientHello message without terminating TLS, enabling routing of TLS connections based on SNI. Used in TCP/UDP stream for pass‑through load balancing.
Q104
How to configure `limit_rate` and `limit_rate_after` for download speed limiting?
Answer: `limit_rate 500k;` limits speed to 500KB/s. `limit_rate_after 1m;` starts limiting only after the first 1MB is transferred. Useful for preventing abuse.
Q105
What is the `ssl_early_data` directive?
Answer: Enables TLS 1.3 0‑RTT (early data), allowing clients to send data in the first flight, reducing latency. Use with caution: early data is replayable. Enable in `server` block: `ssl_early_data on;`.
Q106
How do you handle graceful shutdown of upstream servers in a load‑balanced environment?
Answer: Remove the server from the upstream block, or mark it as `down`: `server backend1 down;`. Then `nginx -s reload`. Active connections to that backend will finish; new connections go elsewhere. Nginx Plus can drain connections via API.
Q107
What is `$upstream_cache_status`?
Answer: A variable that indicates cache status (HIT, MISS, EXPIRED, BYPASS). Add to response header: `add_header X-Cache-Status $upstream_cache_status;` for debugging.
Q108
How to optimize PHP‑FPM with Nginx?
Answer: Use Unix socket, set appropriate `pm` (dynamic/ondemand), `pm.max_children`, `pm.start_servers`. In Nginx, enable `fastcgi_cache`, set `fastcgi_buffers`. Use `fastcgi_param` correctly. Keep `fastcgi_read_timeout` high enough for long‑running scripts.
Q109
What is the difference between `error_log` levels (debug, info, warn, error, crit)?
Answer: `debug` logs everything (only if compiled with `--with-debug`). `info`, `notice`, `warn`, `error`, `crit` in increasing severity. Debugging should never be enabled on production.
Q110
As an intermediate, how would you answer "What is your approach to Nginx security hardening"?
🎤 "I set `server_tokens off;`, hide Nginx version, restrict request methods (`if ($request_method !~ ^(GET|HEAD|POST)$ ) { return 405; }`), limit buffer sizes (`client_body_buffer_size`, `large_client_header_buffers`), disable unwanted modules, enable rate limiting, set modern TLS protocols, and use a WAF like ModSecurity with Nginx. I regularly audit with `nginx -T` and monitor logs."
💎 EXPERT LEVEL
5–10 Years Experience – 60 Q&As
Q121
Design a Nginx‑based architecture to handle 100,000 concurrent connections with dynamic content.
Answer: Use multiple Nginx instances behind an L4 load balancer (e.g., HAProxy or cloud LB). Each Nginx runs on dedicated hardware with tuned kernel (`net.core.somaxconn`, `net.ipv4.tcp_fastopen`). `worker_processes auto; worker_connections 8192; multi_accept on;`. Use `keepalive` connections to upstream with `keepalive 32;`. Enable HTTP/2 and Brotli compression. PHP‑FPM pools on separate servers, with OPcache and Redis session storage. Database with read replicas and connection pooling. Implement aggressive caching (fastcgi_cache, proxy_cache) and use `ngx_http_upstream_dynamic_module` for dynamic upstream. Monitor with `nginx-module-vts` and Prometheus.
Q122
How to implement a custom Nginx module (in C)?
Answer: Write a module conforming to Nginx module structure, define callbacks for configuration, handler, etc. Compile with Nginx using `--add-module=/path/to/module`. Example: a simple handler that returns "Hello". Requires deep C knowledge and understanding of Nginx internals (request phases, memory pools).
👑 MOST EXPERT LEVEL
10+ Years Experience – 40 Q&As
Q181
You are tasked with building a global CDN‑like service using Nginx. What's your approach?
Answer: Deploy Nginx with `ngx_http_slice` and caching at edge points globally, using Anycast or GeoDNS. Implement consistent hashing for cache distribution. Use `proxy_cache_lock` to avoid thundering herd. Write custom module for cache purging and analytics. Integrate with a distributed storage backend. Tune OS network stack heavily. This is extreme‑level, requiring custom development and deep system knowledge.
🎭 SCENARIOS (20 cases)
Scenario: Nginx returns 502 after deployment, but upstream is healthy.
Check `proxy_pass` URL is correct, `resolver` if using domain. Verify firewall between Nginx and upstream allows the port. Check `error_log` for "connect() failed". If using Unix socket, check permissions. Ensure upstream is not overwhelmed; increase `proxy_connect_timeout`.
🧪 LABS (12)
LAB1
Configure Nginx as a reverse proxy for a Node.js app on port 3000.
Create server block with `location / { proxy_pass http://127.0.0.1:3000; proxy_set_header Host $host; }`. Test with curl.
💻 CODE EXERCISES (12)
COD1
Write a shell script to analyze Nginx access log and print top 10 IPs by request count.
#!/bin/bash
awk '{print $1}' /var/log/nginx/access.log | sort | uniq -c | sort -nr | head
🤖 AI TRENDS
AI1
AI‑powered anomaly detection in Nginx logs using ML
Tools like ElastAlert with ML, or cloud services (AWS CloudWatch Logs Insights), can analyze Nginx access/error logs for unusual patterns (spike in 5xx, slow responses, scans) and alert automatically. Some WAF modules use ML for threat detection.
📋 CHEAT SHEET
| Directive | Purpose |
|---|---|
| listen | IP/port to listen on |
| server_name | Hostname matching |
| root | Document root |
| proxy_pass | Reverse proxy URL |
| rewrite | URL rewriting |
| try_files | File existence check |
🎯 Ace Your Next Infrastructure Interview! Visit Our Job Interview Portal
500+ Cloud, Web Server & Programming Q&As | Mock Tests | AI-Powered Prep
🚀 Go to Job Interview Portal – Start Preparing!

0 Comments
thanks for your comments!