How to configure Nginx to serve PHP files with the .php extension?

To configure Nginx to serve PHP files with the .php extension, follow these steps:

  1. Install Nginx and PHP on your server if you have not already done so.

  2. Open the Nginx configuration file using a text editor. The location of this file might differ based on your operating system, but common locations include /etc/nginx/nginx.conf or /etc/nginx/sites-available/default.

  3. Within the server block, locate the location ~ \.php$ block. If it does not exist, create it. This block will be responsible for handling requests for PHP files.

  4. Within the location ~ \.php$ block, ensure it includes the following configuration directives:

    location ~ \.php$ { include snippets/fastcgi-php.conf; fastcgi_pass unix:/run/php/php7.4-fpm.sock; # The socket path may differ based on your PHP version }
  5. Save the changes to the Nginx configuration file and exit the editor.

  6. Restart Nginx to apply the configuration changes. The command to restart Nginx may vary based on your operating system but can be something like sudo systemctl restart nginx.

After completing these steps, Nginx should be configured to serve PHP files with the .php extension.