How to Deny Access to PHP files in NGINX


deny access to php files in nginx

NGINX is a powerful web server that provides plenty of useful features. If you are using NGINX to host your php website, then you might want to deny access to PHP files on your website to make it more secure. Here’s how to deny access to PHP files in NGINX.

 

How to Deny Access to PHP files in NGINX

Here are the steps to deny access to PHP files in NGINX.

 

1. Open NGINX config file

Open NGINX config file in a text editor. Typically, you will find it at /etc/nginx/nginx.conf. Please update it as per your requirement, in the command below.


$ sudo vim /etc/nginx/nginx.conf

 

2. Deny Access to PHP file

PHP files have .php extension. So we will configure NGINX to deny access to all files with .php extension. To do that, add the following block of code to your server config file.

 


location ~\.php$ {
deny all;
error_page 403 =404 / ;
}

In the above code, the users will see a “404: Page not found: error, instead of “403:Access Forbidden” error. If you don’t want that to happen, simply remove the line with “error_page” directive.

 

If you want to deny access to only a few specific IPs, you can use multiple deny statements


location ~\.php$ {
deny 54.34.1.13;
deny 56.44.21.13;
error_page 403 =404 / ;
}

 

If you want to deny access to range of IP addresses (54.34.1.0-54.34.1.255), then use CIDR notation.


location ~\.php$ {
 deny 54.34.1.0/24;
 error_page 403 =404 / ;
}

 

If you want to deny access to all except a few specific IPs, use the allow directive to specify the IP that you want to allow access


location ~\.php$ {
 deny all;
 allow 54.4.1.13;
 allow 54.21.11.10;
 error_page 403 =404 / ;
}

 

You can also use the CIDR notation in allow directive to specify a range of IPs


location ~\.php$ {
 deny all;
 allow 54.34.21.0/24;
 error_page 403 =404 / ;
}

 

3. Reload NGINX Server

Reload NGINX server to apply changes.

$ sudo service nginx reload

About Sreeram Sreenivasan

Sreeram Sreenivasan is the Founder of Ubiq, a business dashboard & reporting platform for small & medium businesses. Ubiq makes it easy to build business dashboards & reports for your business. Try it for free today!