Each HTTP server provides certain features that can be used to optimize request handling and serving content. In this section, we will share some techniques for both Apache and NGINX that can be used to optimize the web server and provide the best performance and scalability. Mostly, when these optimizations are applied, a restart for Apache or NGINX is required.
Mostly, static files, such as images, .css, .js, and fonts don't change frequently. So, it is best practice to cache these static files on the end user machine. For this purpose, the web server adds special headers to the response, which tells the user browser to cache the static content for a certain amount of time. The following is the configuration code for both Apache and NGINX.
Let's have a look at the Apache configuration to cache the following static content:
<FilesMatch "\.(ico|jpg|jpeg|png|gif|css|js|woff)$"> Header set Cache-Control "max-age=604800, public" Apache Configuration </FileMatch> Should be </FilesMatch> </FileMatch>
In the preceding code that has to be placed in a .htaccess file, we used the Apache FilesMatch directive to match the extensions of files. If a desired extension file is requested, Apache sets the headers to cache control for seven days. The browser then caches these static files for seven days.
The following configuration can be placed in /etc/nginx/sites-available/your-virtual-host-conf-file:
Location ~* .(ico|jpg|jpeg|png|gif|css|js|woff)$ {
Expires 7d;
}In the preceding code, we used the NGINX Location block with a case-insensitive modifier (~*) to set Expires for seven days. This code will set the cache-control header for seven days for all the defined file types.
After making these settings, the response headers for a request will be as follows:

In the preceding figure, it can be clearly seen that the .js file is loaded from cache. Its cache-control header is set to seven days or 604,800 seconds. The expiry date can also be noted clearly in the expires headers. After the expiry date, the browser will load this .js file from the server and cache it again for the duration defined in the cache-control headers.