Skip to main content
🌐Networking

📌 Introduction

Every time you open a website, stream a video, or call an API — a web server is doing the heavy lifting behind the scenes. It's the foundational layer that...

📖 8 min read

📌 Introduction

Every time you open a website, stream a video, or call an API — a web server is doing the heavy lifting behind the scenes. It's the foundational layer that receives your request, processes it, and sends back the content you see on your screen.

Despite being one of the most fundamental components in software architecture, web servers are often misunderstood or oversimplified. In this complete guide, we'll go beyond the basics and cover:

  • How web servers actually work (with architecture diagrams)
  • The difference between static and dynamic web servers
  • Apache vs Nginx — when to use which
  • Real configuration examples you can use today
  • Production best practices and security hardening
  • How web servers fit into system design interviews

Whether you're a backend engineer, a full-stack developer, or preparing for system design interviews — this guide has something for you.


⚙️ What is a Web Server?

A web server is software that listens for incoming HTTP/HTTPS requests from clients (browsers, mobile apps, APIs) and responds with the appropriate content — HTML pages, JSON data, images, or files.

At its core, a web server does three things:

  1. Listens on a port (typically port 80 for HTTP, 443 for HTTPS)
  2. Processes the incoming request (routing, authentication, serving files)
  3. Responds with the appropriate content and HTTP status code

Web Server vs Application Server

A common confusion — here's the key difference:

Aspect Web Server Application Server
PurposeServe static content, reverse proxyExecute business logic
ExamplesNginx, ApacheNode.js, Tomcat, Gunicorn
ContentHTML, CSS, JS, imagesDynamic responses from code
ProtocolHTTP/HTTPSHTTP, WebSocket, RPC
Typical RoleFront-facing, handles TLSBehind the web server

In modern architectures, the web server (Nginx/Apache) sits in front and proxies requests to the application server (Node.js/Python/Java) running your actual code.


🧩 How a Web Server Handles a Request

Here's what happens step-by-step when you type a URL in your browser:

Step 1: DNS Resolution

Your browser resolves the domain name to an IP address (e.g., 104.21.45.67) using DNS.

Step 2: TCP Connection + TLS Handshake

A TCP connection is established on port 443, followed by a TLS handshake to encrypt the connection.

Step 3: HTTP Request

Your browser sends an HTTP GET request:

GET /tools/ HTTP/1.1
Host: example.com
Accept: text/html
User-Agent: Mozilla/5.0 ...

Step 4: Web Server Processing

The web server receives the request and decides what to do:

  • Static file? → Serve directly from disk (HTML, CSS, JS, images)
  • Dynamic route? → Forward to the application server via reverse proxy
  • Cached? → Return the cached response immediately

Step 5: HTTP Response

The server sends back the response:

HTTP/1.1 200 OK
Content-Type: text/html; charset=UTF-8
Content-Encoding: gzip
Cache-Control: max-age=3600

<!DOCTYPE html>
<html>...

🔗 Want to explore HTTP concepts hands-on? Try our API & Network Tools — build HTTP requests, decode headers, and inspect status codes right in your browser.


🔧 Types of Web Servers

1. Static Web Server

Serves pre-built files directly from disk. No server-side processing.

Use when: Hosting a blog, documentation site, landing pages, or single-page apps (SPAs).

# Nginx config for static site
server {
    listen 80;
    server_name example.com;
    root /var/www/mysite;
    index index.html;

    location / {
        try_files $uri $uri/ =404;
    }

    # Cache static assets for 30 days
    location ~* \.(css|js|png|jpg|gif|ico|woff2)$ {
        expires 30d;
        add_header Cache-Control "public, immutable";
    }
}

2. Dynamic Web Server (Reverse Proxy)

Forwards requests to an application server that generates responses on the fly.

Use when: Running APIs, web apps with authentication, dashboards, or any app with server-side logic.

# Nginx as reverse proxy to Node.js app
server {
    listen 80;
    server_name api.example.com;

    location / {
        proxy_pass http://127.0.0.1:3000;
        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;
    }
}

3. Load Balancing Web Server

Distributes traffic across multiple backend servers for scalability.

# Nginx load balancing across 3 app servers
upstream backend {
    least_conn;  # Send to server with fewest connections
    server 10.0.0.1:3000;
    server 10.0.0.2:3000;
    server 10.0.0.3:3000;
}

server {
    listen 80;
    location / {
        proxy_pass http://backend;
    }
}

🆚 Apache vs Nginx — Which Should You Use?

The two most popular open-source web servers have different strengths:

Feature Apache Nginx
ArchitectureProcess/thread per connectionEvent-driven, async
PerformanceGood for moderate trafficExcellent for high concurrency
Config.htaccess per-directoryCentralized nginx.conf
ModulesLoaded dynamicallyCompiled at build time
Best forShared hosting, PHP appsReverse proxy, static sites, APIs

When to choose Apache:

  • You need .htaccess for per-directory overrides (shared hosting)
  • Running PHP with mod_php (WordPress, Laravel)
  • Need dynamic module loading

When to choose Nginx:

  • High-traffic sites (10K+ concurrent connections)
  • Reverse proxy in front of Node.js/Python/Go
  • Serving static files or SPAs
  • Microservices architecture

Real-World Usage:

  • Netflix — Nginx for streaming content delivery
  • WordPress.com — Nginx as reverse proxy
  • GitHub — Custom web server layer + Nginx
  • Wikipedia — Apache + Varnish cache

📊 Web Server in System Design Architecture

In system design interviews, the web server is a critical component. Here's how it fits into a typical scalable architecture:

Key architecture points:

  1. CDN serves cached static assets (images, CSS, JS) from edge locations
  2. Load Balancer distributes traffic across multiple web servers
  3. Web Servers handle TLS termination, static files, and proxy to app servers
  4. App Servers run business logic and talk to databases/caches
  5. Horizontal scaling — add more web/app servers as traffic grows

🚀 Setting Up Nginx from Scratch (5-Minute Guide)

Here's a hands-on guide to set up Nginx on Ubuntu:

Install Nginx

# Update packages and install
sudo apt update
sudo apt install nginx -y

# Start and enable on boot
sudo systemctl start nginx
sudo systemctl enable nginx

# Verify it's running
curl http://localhost

Add HTTPS with Let's Encrypt (Free SSL)

# Install Certbot
sudo apt install certbot python3-certbot-nginx -y

# Get certificate (auto-configures Nginx)
sudo certbot --nginx -d example.com -d www.example.com

# Verify auto-renewal
sudo certbot renew --dry-run

🔐 Security Best Practices

1. Always Redirect HTTP to HTTPS

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

2. Rate Limiting

# Limit to 10 requests/second per IP
limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s;

server {
    location /api/ {
        limit_req zone=api burst=20 nodelay;
        proxy_pass http://backend;
    }
}

3. Security Headers

add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-XSS-Protection "1; mode=block" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;

4. Hide Server Version

# In nginx.conf — prevents attackers from knowing your exact version
server_tokens off;

🔗 Test your security setup! Use our Security & Crypto Tools to generate hashes, inspect JWT tokens, and test password strength.


⚡ Performance Optimization Checklist

Optimization Config Impact
Gzip compressiongzip on;60-80% smaller responses
Static file cachingexpires 30d;Eliminates repeat requests
Keep-alivekeepalive_timeout 65;Reuses TCP connections
Worker processesworker_processes auto;Uses all CPU cores
HTTP/2listen 443 ssl http2;Multiplexed requests
sendfilesendfile on;Kernel-level file serving

🎯 System Design Interview Tips

When discussing web servers in interviews, hit these points:

Common questions where web servers matter:

  • "Design a URL shortener" — Web server handles 301/302 redirects
  • "Design a CDN" — Web servers at edge locations serve cached content
  • "Handle 10M requests/second?" — Horizontal scaling with load-balanced Nginx

Key talking points:

  • Stateless design — Store sessions in Redis, not on the web server
  • Horizontal scaling — Add more Nginx instances behind a load balancer
  • TLS termination — Decrypt HTTPS at web server, pass plain HTTP to backend
  • Graceful degradation — Serve cached content when backends are down
  • Health checks — Load balancers ping web servers to detect failures

✅ Summary

Concept Key Takeaway
WhatSoftware that serves HTTP responses to clients
TypesStatic, Dynamic (Reverse Proxy), Load Balancing
PopularNginx (event-driven), Apache (process-based)
SetupInstall → Configure → HTTPS → Optimize
SecurityHTTPS, rate limiting, headers, hide version
ScalingHorizontal scaling + load balancer + CDN
InterviewsStateless, horizontal scaling, TLS termination

🔗 Explore More on SWE Helper


❓ Frequently Asked Questions

What is the primary function of a Web Server?

A web server listens for HTTP/HTTPS requests on a port (typically 80/443), processes the request by either serving a static file from disk or forwarding it to an application server, and returns the appropriate HTTP response with status code, headers, and body content.

What's the difference between Nginx and Apache?

Nginx uses an event-driven, asynchronous architecture — one process handles thousands of connections. Apache uses a process/thread-per-connection model. Nginx excels at high concurrency and reverse proxying. Apache excels at dynamic module loading and .htaccess configuration. For most modern deployments, Nginx is preferred.

Can a web server and application server be the same thing?

Yes — frameworks like Node.js (Express), Python (Flask), and Go's net/http include built-in HTTP servers. However, in production, it's best practice to put Nginx in front as a reverse proxy for TLS termination, static file serving, rate limiting, and handling slow clients.

How do web servers handle thousands of concurrent connections?

Nginx uses an event loop where a single worker process handles many connections asynchronously using OS-level I/O multiplexing (epoll on Linux, kqueue on macOS). This is far more memory-efficient than spawning a thread per connection.

How does HTTPS work with a web server?

The web server performs TLS termination — it decrypts incoming HTTPS traffic using its SSL certificate and private key, then forwards the decrypted request to the backend over plain HTTP (since the internal network is trusted). This offloads encryption work from application servers.

Related Articles