Apache vs. NGINX Web Servers: A Comprehensive Comparison

Apache and NGINX are two of the most widely used web servers on the internet serving billions of web pages daily.

Apache has been around since the mid-1990s and has long been the dominant player in the market, while Nginx introduced in 2004 and has gained popularity even at a faster rate in a shorter time.

Both Apache and NGINX have their own strength and weaknesses but choosing between them is usually not easy because of the overlap in features between the two.

In this post I will compare the design, features, and use cases of each so you can have better understanding of the differences between the two servers and can make an informed decision about which server better fits your requirements..

Differences in Connection Handling Architecture

Apache and Nginx have different approaches to handling web requests, which can have a significant impact on their performance and scalability. In this section, I will explore the differences in connection and request handling models.

Request Handling

One of the main differences between Apache and Nginx is how incoming requests are handled and processed. Apache works on a process model and Nginx uses an event loop to handle incoming requests.

Let’s took at each of these aproaches in detail.

Apache Request Processing Model

Traditionally Apache uses a process-based model to handle incoming requests. What this means is that when a new client establishes a connection with Apache, the handling of the incoming request is assigned to an available process. This means that 100 incoming requests will need 100 Apache processes to handle all the request load.

This approach worked well for small to medium-sized websites but is not scalable when the demand approaches tens of thousands or even more concurrent connections.

As Apache evolved, so did its process model. Let’s examine the various Multi-Processing Modules (MPM) in Apache.

An MPM is a core module responsible for managing connections and dispatching requests to the appropriate processing mechanism. Several MPMs are available for Apache, each with different performance characteristics. Let’s look at the three available models.

1. Prefork MPM

The Prefork MPM uses the original process-based model, where a child process is spawned to handle a single request. This model is used when threads are not offered by the operating system or when security needs require isolation between requests. This is not a scalable model if the need is to serve a significant number of concurrent connections or if the connections are short lived.

2. Worker MPM

The Worker MPM was added later to provide scalability for Apache. It combines the process model with a threaded approach. When using the Worker MPM model, multiple child processes are created each managing its own set of threads. This allows multiple requests to be handled by a single process.

This eliminates the need for ongoing thread creation resulting in a significantly reduced load on the operating system. Worker MPM allows for improved scalability and resource efficiency when compared against Prefork MPM.

3. Event MPM

The Event MPM is similar to the Worker MPM but is designed to address the keep-alive problem. The connetion keep-alive means that a connection from a client is kept open for an extended period of time to handle multiple incoming request. This reduces the TCP connection establishing overhead and results in faster response times.

The Event MPM uses a dedicated thread pool to handle keep-alive connections, freeing up worker threads to process new requests more efficiently.

Process Model

NGINX Event Based Non-Blocking Request Processing Model

Nginx, on the other hand, uses an event based model to service incoming requests. This means that a thread can manage multiple connections simultaneously.

This model uses a non-blocking I/O model where multiple requests can be in the processing queue at the same time. While waiting for an I/O operation to complete, NGINX can service other requests.

Using events, Nginx is able to handle a large number of connections with minimal resource usage.

Nginx does allow the ability to create multiple working processes with each one having its own event queue. Generally, 1-process or thread is allocated per core.

Summary

Each approach has its advantages and disadvantages. The process-based architecture used by Apache allows it to handle complex requests and support a wide range of modules and extensions at the cost of higher resource usage. Nginx’s non-blocking event queue mechanism allows it to scale to a much higher number of incoming connections.

Static vs Dynamic Content

Static vs. Dynamic Content

Main job of a web server is to return data in response to incoming client requests. This data return can either be static, such as a text file or a media asset, or dynamic which is created in response to a request.

Static Content

Static content refers to content that does not change frequently, such as HTML, CSS, and other media files. Static content is served by reading data directly from the file system.

From a design perspective, it is also the easiest form of data to serve and can be returned very quickly. Further static data can be easily cached in memory or on disk.

Both Apache and Nginx are capable of serving static content and do so at a fast speed. Nginx, though is able to process the request and read and write data faster using its non-blocking I/O model. Apache is slower but that gap closes if the configuration is using the event MPM module.

Dynamic Content

Dynamic content is data that is generated in real-time based on client requests or read from a database or other CMS system.

When a request for dynamic data comes to a web server it is forwarded to the appropriate backend for getting these processed.

Apache and Nginx can both serve dynamic content. Apache can use Modules to process dynamic data requests and can also be configured to use FastCGI protocol for dynamic data requests. Nginx uses the FastCGI protocol to communicate with multiple language processing servers such as PHP and Python.

Requests for dynamic data are usually more resource intensive than those for static content.

Performance and Scalability

Performance and scalability are important considerations for a web server.

In the current context, I am referring to performance as the number of requests handled in a given time and scalability being the ability to add horizontal or vertical capacity.

Let’s look at some factors.

Resource Usage

Nginx is a clear winner in this area as it uses a limited number of threads to process incoming requests. Its use of both CPU and memory is lower when compared to Apache.

Apache can be optimized to reduce its resource usage. Some ways to do so are by using a lightweight MPM module, and by removing unused modules from the configuration. To take this a step further, you can also compile Apache code from scratch to have built-in modules instead of dynamically loading the required modules.

Scalability

Scalability is another important factor to consider when choosing a web server. Both Apache and Nginx are capable of handling a large amount of traffic, but they differ in how they scale. Apache can be scaled horizontally, which means that additional servers can be added to handle additional traffic. However, this can be challenging, particularly when it comes to maintaining configuration consistency across multiple servers.

Nginx, on the other hand, is known for being highly scalable. Because it uses an event-based model, it can handle a large number of connections with minimal resource usage. This makes it an ideal choice for high-traffic websites that need to scale quickly and easily. Nginx can also be used as a load balancer, which means that it can distribute traffic across multiple servers to improve performance and reliability.

Speed

Both Apache and Nginx are capable of handling large amounts of traffic, but where they differ is the speed. Because of the design, Nginx is known for being faster than Apache, especially when serving static file content.

Apache is no slouch as it has been continuously optimized over the years, but because of its core design is slower to respond to certain types of requests.

Summary

Both servers are able to handle small and larger websites. But multiple benchmarks have shown that Nginx has consistently outperformed Apache, especially when handling static files.

Check out the most recent benchmark on TechEmpower’s website.

Distributed vs. Centralized Configuration

In this section, I will look into Apache and Nginx configuration files, syntax, and available tools to manage them.

Configuration Files

To manage and store configurations, both Apache and Nginx use files to configure and override server level parameters. Configuration files are also used to manage parameter for built in modules and dynamically loaded modules as well.

Configuration File Syntax

The syntax used by Apache and Nginx is different . Apache used a mix of XML and attribute/value type entries for configuration entries.

### Apache Configuration file

<Directory D:/website>
		Options FollowSymLinks MultiViews
		AllowOverride All
		Require all granted
</Directory>

Nginx, on the other hand, uses a relatively simpler syntax, that uses {} to define configuration blocks. The configuration parameters are defined using attribute/value pairs.

### NGINX Configuration file
 
server {
        listen       80;
        server_name  localhost;

        location / {
            root   html;
            index  index.html index.htm;
       }
}

Let’s get into more detail about the configuration files.

Apache Configuration Files

Linux and Ubuntu

Apache’s main configuration file is named httpd.conf and on Linux is located in the folder /etc/apache2. This file is used for configuring server-level parameters and enabling modules. There is also a ports.conf file within the same folder which defines the ports that Apache will use.

Additional configurations are in the subfolders within the /etc/apache2 folder, including those for Virtual Host configuration.

Shown below are files and folders for Apache configuration on Ubuntu.

user@slap:/etc/apache2$ ls
apache2.conf  conf-available  conf-enabled  envvars  magic  mods-available  mods-enabled  ports.conf  sites-available  sites-enabled

Windows

On Windows, the configuration files are in the {Install Folder}\conf folder. Here httpd.conf is used in a similar manner as to how it is on Linux and other platforms.

Files for modules and additional modules are in the {Install Folder}\conf\extra subfolder.

Shown below is the configuration folder structure.

Directory of C:\apps\apache\httpd\conf

[.]            [..]           charset.conv   [extra]        httpd.conf     magic          mime.types     openssl.cnf    [original]
[ssl]

Apache includes an option to allow additional configurations on a per-directory basis by inspecting and interpreting directives in hidden files within the content folders. These files are known as .htaccess files.

Apache also allows the ability to have domains hosted at the user level as well. The configuration files are maintained by the user in their assigned home directories.

Nginx Configuration Files

Linux and Ubuntu

Nginx configuration files are in the folder /etc/nginx. The main file is nginx.conf where usually server-level parameters are configured. The built-in modules that Nginx has can be configured in nginx.conf file or can be spread across other files as well.

Additional configurations are in the subfolders within the /etc/nginx folder.

Shown below are files and folders for Nginx configuration on Ubuntu.

user@slap:/etc/nginx$ ls
conf.d        fastcgi_params  koi-win     modules-available  nginx.conf    scgi_params      sites-enabled  ssl-certs     win-utf
fastcgi.conf  koi-utf         mime.types  modules-enabled    proxy_params  sites-available  snippets       uwsgi_params

Windows

On Windows, the configuration files are in the {Install Folder}\conf folder. Here httpd.conf is used in a similar manner as to how it is on Linux and other platforms.

Shown below is the configuration folder structure.

Directory of C:\apps\nginx\conf

[.]              [..]             fastcgi.conf     fastcgi_params   koi-utf          koi-win          mime.types       nginx.conf
scgi_params      uwsgi_params     win-utf

Distributed Configuration

Distributed configuration involves splitting configuration files across multiple servers or files. This approach makes it easy to manage complex configurations.

Apache supports distributed configuration through the use of Include directives, which allow the use of multiple files to split configuration parameters.

Nginx also supports distributed configuration by splitting configuration into multiple files.

Note: One main difference is that per directory configurations must be part of the main configuration files.

File vs. URI-based Access

To start this section first I will define both of these access methods.

  • File-based access: When a web request maps directly to a physical file on a web server.
  • URI-based access: A request that maps to a resource that is not an actual file on a web server.

Apache

Apache server has the ability to interpret a resource request to an actual file on the filesystem or as a URI that will map to a web service or some other resource.

For example, if a request, https://example.com/index.html, then that request will be mapped to the file index.html in the root folder of the configured domain.

Apache uses the file-based interpretation approach by default.

This approach works well for serving static content, as a resource request can be mapped directly to an actual file. Apache uses the <Directory> and <File> blocks to map resources to the file system.

Apache web server provides additional alternatives using <Location> and <Alias> to work with URI’s that will map to other dynamic resources.

For example, a request for http://example.com/user/1, might to an external module or script to handle this request.

Nginx

Nginx by default uses a URI-based interpretation approach. It maps incoming requests for resources, defined using regular expressions in the configurtion files to actual files or URIs.

This approach is more flexible and is more suited for requests for dynamic content.

Nginx can also use File based resource mappping using location blocks.

Summary

File-based interpretation is the traditional approach that maps requests to files, while URI-based interpretation is a more modern approach that maps requests to resources based on their URIs.

Apache uses a file-based interpretation approach by default, while Nginx uses a URI-based approach. Although both can be configured to use either resource mapping strategy.

Additional Feature Comparison Between Apache and Nginx

Note: the table below, I provide a comparison between Apache and Nginx in a table format. This list is not exhaustive and can vary depending on the version of Apache or Nginx being used.

FeatureApacheNginx
CachingYesYes
ConfigurationComplex configurationRelatively simple configuration
CPU UsageHigher than Nginx.Low.
Dynamic ModulesYesDoes not support dynamic modules.
Load BalancingYes. Using mod_proxy_balancer.Yes. Built-in support.
Logging and MonitoringFull logging support.

Limited monitoring with mod_status.
Full logging support.

Limited monitoring with ngx_http_status_module.
Memory UsageVulnerable to DDoS attacksMore resistant to DDoS attacks.
Multiple Domain HostingUses Virtual Host configuration blocks.Uses server {}, blocks to support multiple domains.
Operating System SupportSupports most operating systemsSupports most operating systems.

Note: Some features may not be available on Windows. Not recommended for use in production on Windows.
PerformanceLess efficient with high request loadsHighly efficient when handling multiple concurrent requests.
Request HandlingMultiple threads per requestSingle thread handling multiple requests.
Reverse ProxySupports reverse proxy with mod_proxy moduleSupports reverse proxy with inbuilt features.
SecurityVulnerable to DDoS attacks.More resistant to DDoS attacks.
Server ArchitecturePrefork, Worker and Event MPM.Event-driven architecture non-blocking I/O.
SSL/TLS SupportSupports SSL/TLS through mod_ssl.Supports SSL/TLS through the OpenSSL library.
Support and DocumentationLarge user community with extensive documentation.Smaller user community with less extensive documentation but has been growing.

The paid version of the Nginx server, NGINX Plus, is available with commercial support plans.
Apach vs. Nginx Features Comparison

Nginx reverse proxy and cache with load balancing.

Using Apache and NGINX Together

Apache and Nginx are commonly used together in most corporate environments where Nginx works as a reverse proxy and a load balancer and Apache web server is used in the backend hosting dynamic content.

Setting Up Apache and Nginx Integration

Update the server block on Nginx to talk to the backend using the build in proxy module of Nginx. Listed below are high level steps on how to accomplish this.

  1. Install Apache and Nginx on the same or separate servers.
  2. Configure Apache to serve a virtual domain, for example on port 8080.
  3. Configure Nginx to listen to incoming requests on port 80.
  4. Configure Nginx reverse proxy parameters to forward requests to the Apache web server backend.

Sample Nginx location block should be configured similarly to what is shown below.

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

Once the changes are done, Nginx will proxy all incoming requests to the backend Apache server.

Read my post on the complete setup of Nginx as a caching, reverse proxy server with Apache.

Community and Support

Both servers provide extensive documentation, with Apache’s docs more thorough and better organized.

Apache docs.

Nginx docs.

Additional free documentation and support is available on forums such as ServerFault or StackOverflow.

Commercial Support

Apache web sever paid support is available through third-party solution providers. Below is a short list of companies providing support for Apache Web Server.

Nginx offers commercial support options through Nginx, Inc., a company owned by F5 Networks. They provide support subscriptions, consulting, and training. They also provide free access to additional documentation on Nginx, including that for the additional features only available in the paid version of Nginx.

Use Cases and Recommendations

Listed below are some specific use cases for Apache and Nginx web servers.

ApacheNginx
Complex application logicServing static content
Dynamic content with Modules and CGI(PHP, Python)Dynamic content with PHP
Serving static content (low-traffic websites)Load balancing backend services.
Virtual hostingMicroservices
Integrating with Java backend (Tomcat with mod_jk)Reverse proxying
SSL termination
WebSockets
Apache and Nginx Use Cases

Apache and Nginx can both are both popular web servers that are widely used in a variety of contexts. While both web servers offer similar features, they are often used in different ways depending on the specific needs of the website or application. In this section, we will explore some of the common use cases for Apache and Nginx.

Conclusion

You can select either web server and either will work for 90% of the use cases. They both have their unique But when considering edge scenarios one or the other may come on top.

Apache supports a large set of modules, allowing significant customization options. If you depend on any of these modules then Apache is the way to go.

I would also look if you need directory-level customization that the .htaccess files provide. This is an attractive feature that sets Apache apart and makes it a choice for many web hosting companies.

But if I am thinking of a static content website that will be handling high-traffic loads with low resource requirements then Nginx will be my choice.

In most scenarios, though I have found over the years, that Nginx as a front-end as a reverse proxy (or load balancer) for Apache is an excellent combination, providing both horizontal and vertical expansion options.