How to Allow Only POST requests in NGINX


allow only post method in nginx

Sometimes, you may need to allow only POST requests for specific URLs (e.g /login.php) or directories (e.g /uploads). Let us take a look at how to allow only POST requests in NGINX.

 

How to Allow Only POST requests in NGINX

Here are the steps to allow only POST requests in NGINX.

 

1. Open NGINX config file

Open NGINX config file in a text editor. You will generally find it at /etc/nginx/nginx.conf


$ sudo vim /etc/nginx/nginx.conf

 

2. Allow only POST requests

Add the following lines of code depending on your use case. In every case, we use the limit_except directive to limit the allowed methods. You can use it only in location context.

If you want to allow only POST method all over your website


location / {
 limit_except POST {
 deny all;
 }
#rest of your config
}

 

If you want to allow only POST method in a specific directory, such as /uploads/


location ~ ^/uploads/ {
 limit_except POST {
 deny all;
}
#rest of your config
}

 

If you want to allow only POST method in a specific URL,


location ~ ^/admin/login.php {
 limit_except POST {
 deny all;
}
#rest of your config
}

 

3. Reload NGINX web server

Reload NGINX server to apply changes.

$ sudo service nginx reload

 

That’s it! NGINX will not automatically allow only POST methods to your URL or directory.

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!