Nginx

An event-driven web server for static assets, reverse proxying, and distributing requests across application backends.

8 min read 8 lesson sections
  • #http
  • #event-driven
  • #reverse proxy
  • #load balancing
  • #static files
  • #php-fpm
  • #web server
Nginx: An event-driven web server for static assets, reverse proxying, and distributing requests across application backends.
Concept map

Nginx is a web server commonly used to serve static files and act as a reverse proxy. It can return a file directly or pass an application request to an internal service. Nginx does not replace the application’s runtime: PHP, ASP.NET Core, and other applications still run in their own processes.

The event-driven worker model

Nginx uses a master process to manage configuration and worker processes to handle connections. Each worker uses an event loop to work with many network connections without assigning a separate thread to every idle connection.

This design can be efficient for many simultaneous or keep-alive connections. It is not a guarantee that Nginx will outperform every Apache setup: Apache’s event MPM can also handle concurrency well. The application, operating system, modules, TLS settings, and configuration all affect results.

What do the master and worker processes do?

The master process reads configuration and manages workers. It can start workers or reload configuration without dropping every established connection. A worker uses non-blocking event interfaces to track sockets and reads or writes. This does not make application processing itself asynchronous: when Nginx forwards a request to an application, execution time and resource use also depend on that application.

The number of connections a worker can handle depends on worker_connections, operating-system limits, and other resources; there is no one universally correct value. Increasing the worker count alone will not fix a slow backend or exhausted system sockets.

Serving files and routing requests

Nginx configuration is organized around server blocks and location rules. A server block selects a site, and a matching location can return a file, forward a request, or apply another configured action. Static files are served directly; dynamic requests are usually passed to an application service.

For example, this simplified server block forwards requests to an application listening locally on port 5000. It shows HTTP only; configure TLS separately for public traffic:

server {
    listen 80;
    server_name app.example.test;

    location / {
        proxy_pass http://127.0.0.1:5000;
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}

The application must be configured to trust only the appropriate proxy and forwarded headers. Never assume a forwarded client address or scheme is trustworthy when requests can bypass the proxy.

How does Nginx choose a site and path?

Nginx first selects a server block for the listening address and host name, then selects a matching location. Exact matches have special priority; the longest prefix is selected before regular-expression locations are considered, while ^~ can stop regular-expression checks after a prefix match. Rule order matters, so test important paths after configuration changes.

For files, root maps a URL path beneath a filesystem directory. try_files can check whether a file or directory exists before sending the request to a fallback path; this is common for applications that use a front controller. Do not send every request to an application without understanding the effect on private files and missing paths.

This simplified example serves an application that uses index.php and passes PHP to PHP-FPM over FastCGI:

server {
    listen 80;
    server_name php.example.test;
    root /var/www/app/public;
    index index.php;

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    location ~ \.php$ {
        try_files $uri =404;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_pass unix:/run/php/php-fpm.sock;
    }
}

The socket path and included files vary by distribution and PHP version. Test against the installed package, and do not expose project files outside the public directory.

Central configuration and .htaccess

Nginx keeps routing and access rules in its central configuration; it does not read Apache .htaccess files. This gives administrators one place to review the active rules, but it means developers cannot add per-directory server rules by dropping in an .htaccess file.

When migrating from Apache, inventory its rewrite, access, and directory rules first. Translate only the behavior the site needs, test redirects and permissions, then validate the Nginx configuration with the test command for the installed package before reloading.

PHP, ASP.NET Core, and other applications

Nginx serves static content itself. PHP requests are commonly passed to PHP-FPM using FastCGI. For ASP.NET Core, the application runs on Kestrel and Nginx can forward public requests to it over an internal connection. Other services can be routed in the same way using host names or URL paths.

In a reverse-proxy setup, configure the application for the expected forwarded headers and TLS termination. Keep backend ports private where possible, and expose only the routes the public application needs.

Load balancing and operations

Nginx can distribute requests among configured upstream services. Load balancing alone does not make an application reliable: capacity, timeouts, deployment order, and backend health still need a plan. Health-check features and other capabilities can vary by edition, package, and enabled modules.

Backends are commonly declared in an upstream block and referenced by proxy_pass. Nginx can distribute requests using the configured method, such as round robin or consideration of active connections, but a successful request still depends on each backend’s readiness. Load distribution is not the same as application availability; failures, data, and sessions need their own handling and monitoring.

TLS, caching, and request limits

Nginx can terminate TLS and forward requests to a backend over a private network, or use TLS between the layers when required. Configure the application to use forwarded headers only from trusted proxies, and do not accept those values from sources that can bypass the proxy.

Depending on the version, build, and configuration, Nginx can compress responses, cache proxied responses, and limit request rates. These features are not enabled in every build by default. Do not put account pages or responses containing private data in a shared cache without a clear cache-key and invalidation policy.

Understanding the reverse-proxy chain

In client → Nginx → application, the application may see Nginx’s address or the internal HTTP connection instead of the original client address or HTTPS scheme. Proxy configuration can pass values such as Host, X-Forwarded-For, and X-Forwarded-Proto when needed; the application must then trust only the intended proxies. If the application port is publicly reachable, clients may bypass Nginx and supply misleading forwarded headers. Keep the backend private where possible.

Keep configuration changes reviewable, check error logs, and monitor both Nginx and the backends. Caching, request limits, and protocol support depend on the version and modules in use; verify the installed build rather than assuming a feature is enabled.

When Nginx is a good fit

Nginx is often a good fit for a centralized front proxy, static-content delivery, or routing requests to several applications. Apache may be simpler for a site that already relies on its modules or .htaccess rules. Neither server is universally faster, and operating both together adds another configuration and monitoring layer.

To compare the trade-offs before choosing or migrating, see the Apache HTTP Server vs Nginx comparison. Test the same application, traffic, TLS, and caching settings, then compare latency, throughput, CPU, memory, and errors.

Diagnosis and measurement

Many Linux installations provide nginx -t to test configuration, nginx -T to show the loaded configuration, and nginx -V to show the version and build options; commands and permissions vary by package. When a server error appears or a backend cannot be reached, inspect both Nginx and application logs.

To isolate a routing issue, verify the selected server name, the matching location, the file’s existence and read permission, and finally the backend’s health. Test a static request and a dynamic request separately. For performance tests, record request rate, P95/P99 latency, Nginx and backend resource use, and error rate. Keep TLS and caching settings consistent so the results are meaningful.

Official references