HSR Sector 6 · Bangalore +91 96110 27980 Mon–Sat · 09:30–20:30
Chapter 13 of 20 — Linux Administration
intermediate Chapter 13 of 20

Web Servers on Linux — Apache & Nginx Installation and Config

By Vikas Swami, CCIE #22239 | Updated Mar 2026 | Free Course

Web Server Fundamentals — HTTP, Ports & Request Flow

Understanding the foundational concepts of web servers is essential before diving into specific implementations like Linux web server Apache Nginx. At the core, web servers facilitate communication between clients (browsers) and servers, primarily using the Hypertext Transfer Protocol (HTTP). HTTP defines how messages are formatted and transmitted, enabling web browsers to retrieve resources such as HTML pages, images, and scripts from servers.

HTTP operates over TCP/IP protocols, commonly on port 80 for HTTP and port 443 for HTTPS. When a user enters a URL, the browser initiates a TCP connection to the server's IP address on the designated port. The server then processes the request, fetches the required resource, and responds with an HTTP status code along with the requested data. This request-response cycle is fundamental to web hosting on Linux servers, where configuring ports correctly is crucial for service accessibility.

Request flow begins with the client sending an HTTP request, which includes methods like GET, POST, PUT, or DELETE. The server interprets this request, processes it—possibly interacting with databases or backend services—and returns an HTTP response. Proper understanding of this flow is vital, especially when configuring web servers like Apache and Nginx, which act as intermediaries handling incoming traffic efficiently and securely.

Apache HTTP Server — Installation, Virtual Hosts & .htaccess

Apache HTTP Server remains one of the most widely used open-source web servers for Linux due to its robustness, modularity, and extensive configuration options. Installing Apache on a Linux system involves a straightforward process, typically using the package manager of your distribution. For Ubuntu/Debian systems, execute:

sudo apt update
sudo apt install apache2

Once installed, the service can be managed via systemctl commands:

sudo systemctl start apache2
sudo systemctl enable apache2
sudo systemctl status apache2

Configuring Virtual Hosts allows hosting multiple websites on a single server, each with its own domain or subdomain. Virtual Host configurations are stored in /etc/apache2/sites-available/. An example configuration for a domain example.com:


    ServerName example.com
    ServerAlias www.example.com
    DocumentRoot /var/www/example.com/public_html
    ErrorLog ${APACHE_LOG_DIR}/example.com_error.log
    CustomLog ${APACHE_LOG_DIR}/example.com_access.log combined

Enabling the site and restarting Apache:

sudo a2ensite example.com.conf
sudo systemctl reload apache2

Another powerful feature is the use of .htaccess files, which allow directory-level configuration without modifying main server config files. Common uses include URL rewriting, access control, and custom error pages. For example, enabling URL rewriting involves:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?$1 [QSA,L]

This flexibility makes Apache an ideal choice for Linux web hosting environments where granular control over web directory behavior is necessary.

Nginx — Installation, Server Blocks & Configuration Syntax

Nginx has gained popularity as a high-performance, scalable web server and reverse proxy, especially in Linux web hosting scenarios. Its event-driven architecture enables handling a large number of concurrent connections with minimal resource consumption. To install Nginx on a Linux system, run:

sudo apt update
sudo apt install nginx

Once installed, the service can be started and enabled using:

sudo systemctl start nginx
sudo systemctl enable nginx
sudo systemctl status nginx

Configuring server blocks in Nginx replaces Apache's Virtual Hosts. These are stored in /etc/nginx/sites-available/ and linked to /etc/nginx/sites-enabled/. A typical server block for example.com looks like:

server {
    listen 80;
    server_name example.com www.example.com;
    root /var/www/example.com/public_html;

    index index.html index.htm index.php;

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

    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
    }

    error_log /var/log/nginx/example.com_error.log;
    access_log /var/log/nginx/example.com_access.log;
}

Configuration syntax in Nginx is concise yet powerful, relying on directives within server blocks. Reloading configuration after changes is done via:

sudo nginx -s reload

Nginx's configuration syntax emphasizes simplicity and efficiency, making it suitable for serving static content, acting as a reverse proxy, or load balancer in complex web hosting setups.

Apache vs Nginx — Architecture, Performance & Use Cases

Aspect Apache Nginx
Architecture Process-driven with multi-threading or process for each connection. Uses a hybrid model with worker or event MPM modules. Event-driven, asynchronous architecture that handles multiple connections within a single thread, optimizing resource use.
Performance Excellent for dynamic content and complex configurations but may consume more resources under high load. Superior for serving static content and high concurrency environments due to its non-blocking design.
Use Cases Hosting complex websites requiring .htaccess, dynamic content (PHP, Python), granular access control. High-traffic sites, reverse proxy, load balancing, microservices, static content delivery.
Configuration More verbose and flexible; allows directory-level directives via .htaccess. Simpler syntax; configuration centralized in server blocks without per-directory overrides.
Module System Extensible via modules, often compiled into the core or loaded dynamically. Modules are dynamically loaded; less flexible than Apache but more performance-oriented.

Choosing between Apache and Nginx depends on specific project needs. Apache is favored when fine-grained control over directory behavior and dynamic content is essential, whereas Nginx excels in high-performance, scalable environments. For comprehensive server setup guidance, visit Networkers Home for expert training.

SSL/TLS Setup — Let's Encrypt, Certbot & HTTPS Configuration

Securing your Linux web server with SSL/TLS certificates is crucial for protecting data and establishing trust with users. Let's Encrypt provides free, automated certificates, and Certbot simplifies their deployment. To install Certbot on Ubuntu/Debian:

sudo apt update
sudo apt install certbot python3-certbot-nginx  # For Nginx
sudo apt install certbot python3-certbot-apache # For Apache

Obtaining and installing a certificate involves running:

sudo certbot --nginx  # For Nginx
sudo certbot --apache # For Apache

Certbot will prompt for domain names, email, and agree to terms. It automatically configures the server for HTTPS, including redirect rules to enforce secure connections. To verify renewal, test the setup with:

sudo certbot renew --dry-run

Regular renewal is automated via cron jobs, ensuring your web server always maintains valid certificates. Proper SSL/TLS setup not only boosts security but also improves SEO rankings and user confidence.

Reverse Proxy & Load Balancing with Nginx

Nginx is widely used as a reverse proxy, distributing incoming traffic across multiple backend servers to enhance scalability and reliability. Setting up a reverse proxy involves configuring a server block that forwards requests to application servers, often on different ports or machines. Example configuration:

server {
    listen 80;
    server_name example.com;

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

This setup forwards requests to a backend service running on port 8080. For load balancing, Nginx can distribute traffic across multiple servers:

upstream app_servers {
    server 192.168.1.101;
    server 192.168.1.102;
}

server {
    listen 80;
    server_name example.com;

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

Implementing reverse proxy and load balancing significantly improves application availability and performance, especially for high-traffic websites and web applications. Advanced configurations include SSL termination, session persistence, and health checks, making Nginx a versatile tool in Linux web hosting.

PHP, Python & Node.js — Integrating Application Backends

Modern web servers often serve dynamic content generated by backend applications written in PHP, Python, or Node.js. Integrating these with Apache or Nginx involves configuring server modules and handlers:

PHP Integration

Apache uses mod_php or PHP-FPM for efficient processing. For example, enabling PHP-FPM with Apache:

sudo apt install php-fpm libapache2-mod-php
sudo a2enconf php7.4-fpm
sudo systemctl restart apache2

Nginx relies solely on PHP-FPM. A typical PHP setup involves editing the server block to include:

location ~ \.php$ {
    include snippets/fastcgi-php.conf;
    fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
}

Python & Node.js

Python web applications often run via WSGI servers like Gunicorn or uWSGI, proxied through Nginx. Example Nginx config snippet:

location /app/ {
    proxy_pass http://127.0.0.1:8000/;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}

Node.js servers typically run on specific ports and are reverse-proxied similarly. Ensuring proper configuration and resource allocation is critical for high-performance web hosting. For detailed guidance, refer to Networkers Home Blog.

Web Server Security, Logging & Performance Tuning

Securing Linux web servers involves multiple layers: configuring firewalls (e.g., ufw or firewalld), disabling unnecessary modules, and enforcing HTTPS. Regularly updating server software patches patches known vulnerabilities. For Apache and Nginx, security best practices include:

  • Restricting directory access with proper permissions.
  • Implementing rate limiting and IP blocking.
  • Using security headers like Content Security Policy (CSP) and X-Content-Type-Options.
  • Enabling logging for audit and troubleshooting purposes.

Log files such as /var/log/apache2/ and /var/log/nginx/ provide insights into traffic patterns, errors, and potential attacks. Log analysis tools like GoAccess or AWStats assist in monitoring.

Performance tuning includes adjusting worker processes, buffer sizes, and enabling caching mechanisms like mod_cache in Apache or proxy_cache in Nginx. Additionally, enabling Gzip compression reduces bandwidth usage, accelerating content delivery. Proper tuning ensures your Linux web server Apache Nginx delivers optimal performance under load.

Key Takeaways

  • Understanding HTTP, ports, and request flow is fundamental to effective web server setup on Linux.
  • Apache offers extensive configurability with Virtual Hosts and .htaccess, ideal for complex dynamic sites.
  • Nginx provides high performance, efficient resource utilization, and is suitable for reverse proxy and load balancing roles.
  • SSL/TLS with Let's Encrypt and Certbot is essential for securing web traffic and building user trust.
  • Configuring reverse proxy and load balancing enhances scalability and resilience of web applications.
  • Integrating PHP, Python, and Node.js enables serving dynamic content seamlessly with both servers.
  • Security, logging, and performance tuning are critical components of reliable web hosting infrastructure.

Frequently Asked Questions

How do I choose between Apache and Nginx for my Linux web server?

Choosing between Apache and Nginx depends on your specific needs. Apache provides extensive modules, .htaccess support, and is ideal for complex, dynamic websites requiring granular control. Nginx excels in high concurrency environments, serving static content efficiently, and acting as a reverse proxy or load balancer. Consider factors like traffic volume, application complexity, and server resources. For most high-traffic web hosting scenarios, Nginx offers superior performance, whereas Apache is preferred for applications relying heavily on directory-level configuration. Both servers can be used together to leverage their strengths in a hybrid setup, which is common in enterprise environments. For tailored guidance, visit Networkers Home.

What are the steps to set up HTTPS on a Linux web server using Let's Encrypt?

Securing your Linux web server involves installing Certbot, the recommended tool for obtaining free SSL certificates from Let's Encrypt. First, update your package list and install Certbot along with the appropriate plugin for your server (Nginx or Apache). Next, run the Certbot command with your server type, e.g., sudo certbot --nginx or sudo certbot --apache. Follow prompts to specify your domain and email. Certbot automatically updates your server configuration to redirect HTTP to HTTPS. Verify the setup by visiting your website with https://. Regular renewal checks are handled automatically, but you can test renewal with sudo certbot renew --dry-run. Proper SSL setup encrypts data in transit, bolsters security, and improves SEO rankings.

How can I configure a reverse proxy using Nginx for multiple backend servers?

Configuring a reverse proxy in Nginx involves defining a server block with proxy_pass directives pointing to your backend servers. To load balance across multiple servers, define an upstream group:

upstream my_app {
    server 192.168.1.101;
    server 192.168.1.102;
}
Then, create a server block that proxies requests to this group:

server {
    listen 80;
    server_name example.com;

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

This setup distributes client requests evenly, ensuring high availability and load distribution. Adjust health checks and session persistence as needed for more advanced configurations. For detailed tutorials, check out Networkers Home Blog.

Ready to Master Linux Administration?

Join 45,000+ students at Networkers Home. CCIE-certified trainers, 24x7 real lab access, and 100% placement support.

Explore Course