Increase PHP script execution time with Nginx
Hatched by Felipe Soares Barbosa Silveira (Felipebros)
Sep 27, 2023
4 min read
9 views
Increase PHP script execution time with Nginx
In today's digital world, speed and efficiency are paramount when it comes to web development. As developers, we constantly strive to optimize our code and server configurations to ensure our applications run smoothly and quickly. One area that often requires attention is the execution time of PHP scripts. By default, PHP has a set maximum execution time for scripts, but there are times when we may need to increase this limit to accommodate more complex or time-consuming tasks. In this article, we will explore how to increase PHP script execution time with Nginx, a popular web server and reverse proxy server.
To begin, let's first understand why we might need to increase the PHP script execution time. In Apache, applications running PHP as a module above would have sufficed. However, when using Nginx, we need to make this change in three different places: in the php.ini file, in the PHP-FPM configuration, and in the Nginx configuration. Each of these steps plays a crucial role in increasing the execution time.
The first step is to make changes in the php.ini file. This file contains various configuration settings for PHP, including the maximum execution time for scripts. Open the php.ini file and locate the "max_execution_time" directive. By default, this value is set to 30 seconds. Increase it to a higher value that suits your needs, such as 60 seconds or even higher if necessary. Save the changes and restart your PHP service for the changes to take effect.
Next, we need to make changes in the PHP-FPM configuration. PHP-FPM is a FastCGI process manager for PHP that allows for better performance and flexibility. Locate the PHP-FPM configuration file, usually located at /etc/php-fpm.conf or /etc/php-fpm.d/www.conf. Look for the "request_terminate_timeout" directive and increase its value to match the maximum execution time set in the php.ini file. Save the changes and restart the PHP-FPM service.
Finally, we need to update the Nginx configuration to reflect the changes made in the previous steps. Open the Nginx configuration file, usually located at /etc/nginx/nginx.conf or /etc/nginx/sites-available/default. Locate the location block that handles PHP scripts, which is usually indicated by a location ~ .php$ directive. Add the following line within this block:
fastcgi_read_timeout {max_execution_time}s;
Replace {max_execution_time} with the maximum execution time set in the php.ini file. Save the changes and restart the Nginx service for the changes to take effect.
Sources
Hatch New Ideas with Glasp AI 🐣
Glasp AI allows you to hatch new ideas based on your curated content. Let's curate and create with Glasp AI :)
Start Hatching 🐣