How to restrict access to certain files or directories based on file extensions in Nginx?

To restrict access to certain files or directories based on file extensions in Nginx, you can use the "location" directive along with "deny" or "allow" directives. Here's how you can do it:

  1. Open your Nginx configuration file. The location of this file can vary depending on your system setup but common locations are "/etc/nginx/nginx.conf" or "/etc/nginx/sites-available/default".

  2. Inside the "http" block or your specific server block, add a new location block for the directory or files you want to restrict access to. For example, to restrict access to files with ".php" extension:

location ~ \.php$ { deny all; }

This location block uses a regular expression to match all files ending in ".php".

  1. Save the configuration file and reload Nginx to apply the changes:
sudo service nginx reload

With the above configuration, Nginx will deny access to any file with a ".php" extension. You can modify the regular expression or use different directives like "allow" instead of "deny" to suit your specific requirements.