Skip to content
Tutorials Center
My learning

Topics

Lesson 16 of 30 ยท Proxying and Load Balancing

Nginx in Front of Apache

Put nginx in front of Apache: who does what, passing the real client IP with mod_remoteip, avoiding double compression, port layout and when the stack is not worth it.

Many production servers run both programs: nginx listens on ports 80 and 443 and Apache sits behind it on a private port such as 8080. This looks redundant, but it solves a real problem. A lot of existing software (WordPress sites, older PHP applications, anything that depends on .htaccess files and mod_rewrite rules) was built for Apache. nginx is better at holding many connections open, serving static files and terminating TLS cheaply. Combining them keeps Apache's compatibility without paying for Apache's per-connection cost on every slow client.

This lesson covers who should do which job, the configuration on both sides, how to get the real client address through two layers, and how to avoid a classic mistake, double compression. It also tells you when the combination is not worth the trouble. If you have not read Reverse Proxy Basics and Nginx vs Apache: Architecture and Choosing, start there.

Two tiers, two jobs

nginx (edge) TLS, static files, slow clients.
Apache (origin) .htaccess, mod_rewrite, PHP.
Private port Apache listens on loopback only.
1 / 2

Who does what

A sensible split looks like this:

Job nginx Apache
Accept connections from the internet yes no, loopback only
TLS certificates and HTTP/2 yes no
Static files (/assets, images, CSS, JS) yes, straight from disk only if nginx does not know the path
.htaccess, mod_rewrite, mod_php no yes
Rate limiting, caching of whole responses yes rarely
Application logic no yes

The big win is the static-file path. Most pages need ten or more static requests for each dynamic one, and nginx answers those without Apache ever waking a worker. Apache is left with the requests that actually need its modules.

Configuring nginx at the edge

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

    # Static files served directly. If a file does not exist, fall through to Apache.
    location / {
        try_files $uri @apache;
    }

    location @apache {
        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;
    }

    # Files that must never be served directly, even though they sit under root.
    location ~ /\.(ht|git) { deny all; }
    location ~* \.php$     { proxy_pass http://127.0.0.1:8080; }
}

try_files $uri @apache checks the disk first and sends everything that is not a real file to the named location @apache. PHP files are never served as static files, so they are sent straight to Apache with the explicit .php location. (A regex location wins over the prefix /, as explained in Location Blocks and Matching Order.) The deny rule matters because nginx would otherwise serve a .htaccess file as plain text when it finds one under root: nginx does not interpret that file, but it must not leak it.

Remember that both programs need to see the same files: Apache's DocumentRoot and nginx's root must point to the same directory, and the nginx user must be able to read it.

Configuring Apache behind it

Apache moves to a private address and port. Edit ports.conf (Debian-style) or the Listen line so that it does not compete with nginx:

APACHE
Listen 127.0.0.1:8080

<VirtualHost 127.0.0.1:8080>
    ServerName example.com
    ServerAlias www.example.com
    DocumentRoot /var/www/example/public

    <Directory /var/www/example/public>
        AllowOverride All
        Require all granted
    </Directory>

    RemoteIPHeader X-Forwarded-For
    RemoteIPInternalProxy 127.0.0.1
</VirtualHost>

Binding to 127.0.0.1 means nobody can reach Apache without going through nginx, so none of nginx's limits or filters can be bypassed. After changing Listen, restart Apache and check with ss -ltnp that it no longer listens on the public address.

Getting the real client IP: mod_remoteip

From Apache's point of view, every connection comes from 127.0.0.1, so access logs, Require ip rules and the REMOTE_ADDR that PHP reads are all wrong. mod_remoteip repairs this: you name the header (RemoteIPHeader X-Forwarded-For) and the proxies you trust (RemoteIPInternalProxy, or RemoteIPTrustedProxy). When a request arrives from a trusted proxy, Apache replaces its idea of the client address with the last untrusted address in the header. Requests from anyone else are not rewritten, so a visitor who sends a fake header gains nothing.

Enable it with a2enmod remoteip on Debian-style systems. In access logs, %a prints the client address as mod_remoteip rewrote it, and %{c}a prints the address of the underlying connection (nginx). Check your own LogFormat after enabling the module.

Always list the proxies you trust. Only addresses that you list may speak for the client, which is what stops a visitor from choosing their own address with a fake header.

Avoiding double compression

Compression is the classic mistake in a two-tier stack. If Apache's mod_deflate compresses a response and nginx's gzip on then compresses the same bytes, you spend CPU twice and gain nothing, because compressed data barely shrinks. Worse, some setups end up with Content-Encoding: gzip, gzip, which browsers do not decode.

nginx protects you partly. Its gzip module does not compress a response that already has a Content-Encoding header. But the safest design is to compress in exactly one place, and that place should be the edge:

  • Turn compression on in nginx (gzip on;, see HTTP/2, HTTP/3, gzip and Brotli).
  • Turn it off in Apache (a2dismod deflate), or have nginx ask Apache for uncompressed data with proxy_set_header Accept-Encoding ""; in the proxy location. This is the clean fix: Apache then never sees that the client accepts gzip, so it does not compress, and nginx does it once for the client.

The following stand-in builds two tiers in Node.js on loopback: an edge that serves a static file from memory and forwards everything else, and an origin standing in for Apache, which also uses mod_remoteip logic. The first TryIt prints the headers at each hop so you can see the client address survive.

Node.js A two-tier pipeline, header by header

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

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The static request never reaches the origin: the edge answers it from its own storage. The dynamic request reaches the origin with a TCP peer of 127.0.0.1, which is useless, and an X-Forwarded-For list ending with the address the edge accepted. The mod_remoteip logic walks the list from the right, skips trusted proxies and lands on the real client. This is a model of the algorithm described above, not Apache's code, which also supports CIDR ranges, a separate proxy-protocol option and more.

Now the compression half of the story. Node's built-in zlib does the same DEFLATE work that mod_deflate and nginx's gzip do, so the sizes are realistic for a text response.

Node.js What double compression costs

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

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Compressing the already compressed data does not help: the second pass makes the response slightly larger (by 23 bytes in a typical run) and costs CPU for nothing. The practical lesson is the one above: pick one place, and let nginx do it.

Ports, TLS and the scheme

Only nginx should hold the certificates. Apache then sees plain HTTP on loopback and cannot tell the visitor used HTTPS, which is why the X-Forwarded-Proto header matters. Most PHP applications look at $_SERVER['HTTPS'], so configure Apache to set it from the header:

APACHE
SetEnvIf X-Forwarded-Proto "https" HTTPS=on

Application frameworks also have settings for this ("trusted proxies" in Laravel, SECURE_PROXY_SSL_HEADER in Django). Without them you will meet endless redirects from http to https, which the app keeps issuing because it believes the visitor is on plain HTTP.

When it is not worth it

Two web servers mean two configs, two sets of logs, two things to patch and a longer path for every dynamic request. Do not add nginx in front of Apache when:

  • traffic is small and Apache's event MPM already copes comfortably;
  • a CDN or load balancer already terminates TLS and serves static files;
  • the application is moving away from .htaccess, in which case migrating to nginx plus PHP-FPM (PHP, FastCGI and Application Servers) removes a tier;
  • you cannot reliably keep the two configs in sync.

Do add it when you serve large amounts of static content, many slow clients, or HTTP/2 and HTTP/3 to the outside world while keeping an Apache-only application running unchanged.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does Apache behind nginx log 127.0.0.1 for every visitor, and how do you fix it?

    Apache's peer is the proxy. mod_remoteip replaces the address with the one from the forwarded header, but only for requests that come from trusted proxies.
  2. 2. What is the cleanest way to avoid compressing twice?

    Compressed data barely shrinks again, so the second pass wastes CPU and may even produce a double Content-Encoding. One compressor at the edge is simpler.
  3. 3. Why should Apache listen on 127.0.0.1:8080 in this setup?

    Binding to loopback makes nginx the only way in, so its limits, filters and TLS cannot be skipped.
  4. 4. Which combination is a good reason for nginx in front of Apache?

    Apache keeps the compatibility, nginx absorbs the static files and connection load. The other cases gain little from a second tier.

Summary

  • nginx at the edge handles TLS, HTTP/2, static files and slow clients; Apache behind it keeps .htaccess, mod_rewrite and PHP working.
  • Bind Apache to 127.0.0.1 on a private port so nginx cannot be bypassed.
  • Pass Host, X-Forwarded-For and X-Forwarded-Proto; use mod_remoteip with a trusted proxy list so Apache sees the real client.
  • Compress in one place only; never let both tiers gzip the same response.
  • Skip the combination when a CDN already does the edge work or the site is small.

Next: turn on HTTPS properly in HTTPS, TLS and Let's Encrypt.