Wrong Webroot with Atomic Deployments and PHP FPM

If using Nginx and PHP FPM as a web server solution, then you might have experienced a strange issue involving atomic deployment strategies for your web application.

Atomic deployment solutions, such as Capistrano, create a symlink to the current application release directory. When a new deployment takes place, Capistrano simply updates the symlink to the new build once the new build folder is ready.

PHP FPM can sometimes create a strange scenario where PHP scripts were being executed from the old build folder. For example, some PHP code may reside in an index.php file that generates a .txt file. Upon executing the code, the .txt file is created in the old build folder instead of the new build directory. This can be problematic for applications that may generate files such as sitemaps and search engine robots files.

So why does the issue exist? Take a look at the Nginx configuration file responsible for serving your application and locate the following line.

fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;

Replace $document_root with $realpath_root.

fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;

This allows Nginx to pass the actual scripts path and any caching issues involving paths to the build directories will be resolved.

Reload the Nginx configuration to update the changes. As always, test the Nginx configuration before reloading to ensure the configuration syntax is correct.

$ sudo nginx -t && sudo service nginx reload