Console Login

Nginx as a Reverse Proxy: Stop Your Apache Server from Choking on Traffic

Nginx as a Reverse Proxy: Stop Your Apache Server from Choking on Traffic

Let’s be honest: Apache is a beast, but it is a heavy beast. If you are running a standard LAMP stack (Linux, Apache, MySQL, PHP) on a VPS with limited RAM, you have likely seen the dreaded MaxClients reached error in your logs. Your site crawls, your memory swap goes through the roof, and your visitors bounce. In the hosting world of 2011, throwing more hardware at the problem is the lazy man's solution. The smart solution is architecture.

Enter Nginx. While Apache spawns a heavy process or thread for every single connection, Nginx uses an event-driven, asynchronous architecture. It can handle thousands of concurrent connections with a tiny memory footprint. By placing Nginx in front of Apache as a reverse proxy, you get the best of both worlds: Nginx handles the high concurrency and static files (images, CSS, JS), while Apache stays behind the scenes doing what it does best—processing dynamic PHP scripts.

In this guide, I will show you how to configure this setup on a CentOS 6 system. We will also touch on why hardware choice—specifically the underlying virtualization used by your provider—matters just as much as your software config.

The Architecture: Why This Works

In a standard setup, when a user requests an image file, Apache wakes up, consumes several megabytes of RAM, sends the file, and goes back to sleep (or waits in KeepAlive). If you have 500 users, that is 500 fat processes eating your RAM.

With a Reverse Proxy setup:

  1. Nginx (Port 80): Accepts all incoming connections. It serves static files instantly from disk/memory.
  2. Apache (Port 8080): Only receives requests for dynamic content (like .php files) forwarded by Nginx.

This drastically reduces memory usage because Apache is no longer tied up sending slow JPEGs over high-latency mobile connections.

Step 1: Installing Nginx on CentOS

Standard CentOS repositories do not include Nginx yet. We need the EPEL (Extra Packages for Enterprise Linux) repository. If you are hosting on a CoolVDS instance, your network throughput to the mirrors is likely already optimized, but let's make sure we get the packages fast.

# Install EPEL repository rpm -Uvh http://download.fedoraproject.org/pub/epel/6/i386/epel-release-6-5.noarch.rpm # Install Nginx yum install nginx # Turn on Nginx at boot chkconfig nginx on

Step 2: Reconfiguring Apache

We need Apache to stop listening on port 80 so Nginx can take over. We also need to ensure Apache logs the real visitor IP, not just 127.0.0.1 from Nginx.

Edit your /etc/httpd/conf/httpd.conf:


# Change the Listen directive
Listen 127.0.0.1:8080

# Ensure KeepAlive is off for Apache (let Nginx handle it)
KeepAlive Off

Pro Tip: The Real IP Problem
When Nginx proxies to Apache, Apache sees the request coming from localhost. To fix this, install mod_rpaf (Reverse Proxy Add Forward). This module grabs the X-Forwarded-For header sent by Nginx and resets the remote IP address in Apache. Without this, your allow/deny rules and access logs are useless.

Step 3: Configuring Nginx as the Proxy

Now for the meat of the configuration. We will edit /etc/nginx/nginx.conf (or create a virtual host file in /etc/nginx/conf.d/yoursite.conf).

Here is a battle-tested configuration block optimized for a server with 2GB - 4GB RAM:


server {
    listen       80;
    server_name  www.example.com example.com;

    # 1. Serve Static Content Directly
    location ~* \.(jpg|jpeg|gif|png|css|js|ico|xml)$ {
        access_log        off;
        log_not_found     off;
        expires           30d;
        root              /var/www/html;
    }

    # 2. Pass Dynamic Content to Apache
    location / {
        proxy_pass         http://127.0.0.1:8080/;
        proxy_redirect     off;

        proxy_set_header   Host             $host;
        proxy_set_header   X-Real-IP        $remote_addr;
        proxy_set_header   X-Forwarded-For  $proxy_add_x_forwarded_for;
        
        client_max_body_size       10m;
        client_body_buffer_size    128k;

        proxy_connect_timeout      90;
        proxy_send_timeout         90;
        proxy_read_timeout         90;

        proxy_buffer_size          4k;
        proxy_buffers              4 32k;
        proxy_busy_buffers_size    64k;
        proxy_temp_file_write_size 64k;
    }
}
SysAdmin Note: Pay attention to proxy_buffers. If your PHP scripts output a lot of data, Nginx needs enough buffer space to hold the response before sending it to the client. If the buffer is too small, Nginx will write to a temporary file on the disk, killing your I/O performance.

The Hardware Reality: Why Virtualization Matters

You can optimize your configs all day, but if your underlying host is overselling resources, you will still experience lag. This is common with budget providers using OpenVZ containers where "guaranteed RAM" is more of a suggestion than a rule.

This is where CoolVDS differs. By utilizing KVM (Kernel-based Virtual Machine) virtualization, resources are hard-allocated. When you buy 4GB of RAM, that memory block is dedicated to your kernel. Furthermore, disk I/O—often the bottleneck in database-heavy applications—is critical. While many hosts are still spinning 7.2k SATA drives, moving to SSD storage (Solid State Drives) or high-RPM SAS arrays can reduce database query latency by an order of magnitude.

Latency and Local Compliance

If your target audience is in Norway, latency to the NIX (Norwegian Internet Exchange) in Oslo is a metric you cannot ignore. Serving a request from a datacenter in Texas adds ~140ms of round-trip time. Serving it from a local node adds ~5ms.

Additionally, we must consider the Personal Data Act (Personopplysningsloven) and the mandates from Datatilsynet. Keeping customer data within Norwegian borders or the EEA ensures you are compliant with current regulations regarding data privacy. Using a US-based host puts you under the jurisdiction of the Patriot Act, which is a headache most Norwegian CTOs prefer to avoid.

Testing the Configuration

Before you restart services, always check your syntax. A typo in nginx.conf will bring your site down.

# Check syntax nginx -t # If successful: /etc/init.d/httpd restart /etc/init.d/nginx start

Once running, use top or htop. You should see Apache processes dropping in number and memory usage stabilizing, while Nginx handles the connections with barely any CPU load.

Final Thoughts

Implementing Nginx as a reverse proxy is the single most effective change you can make to a LAMP stack in 2011 without rewriting your code. It stabilizes your load, speeds up static content delivery, and prepares your infrastructure for scaling.

However, software is only half the equation. Don't let slow I/O or oversold RAM kill your SEO efforts. For mission-critical applications where milliseconds count, you need dedicated resources and fast storage.

Ready to see the difference? Deploy a test instance on CoolVDS today and experience the stability of KVM virtualization paired with premium connectivity.