How to configure Nginx to restrict access to PHP files based on file extensions?

To configure Nginx to restrict access to PHP files based on file extensions, you can follow these steps:

  1. Open the Nginx configuration file for your website or virtual host. This file is usually located in /etc/nginx/sites-available/ or /etc/nginx/conf.d/.

  2. Locate the server block or location block where you want to add the restriction. Inside the block, add the following code:

location ~ \.php$ { deny all; }

This code uses a regular expression to match any file ending with .php and denies access to it.

  1. Save the configuration file and exit the editor.

  2. Test the Nginx configuration to make sure there are no syntax errors:

sudo nginx -t
  1. If the test is successful, reload Nginx to apply the changes:
sudo systemctl reload nginx

After following these steps, Nginx will deny access to any PHP file requested on your website or virtual host.