How to Allow Only POST requests using .htaccess in Apache


allow only post requests using .htaccess

Sometimes, you might want to allow only POST requests on your website, or in a specific directory. Here’s how you can allow only POST requests using .htaccess in Apache.

 

How to Allow Only POST requests using .htaccess in Apache

Here are the steps to allow only POST requests using .htaccess in Apache and deny all other request methods. Before you proceed, please ensure you have enabled .htaccess on your Apache web server. Here are the steps to do it:

 

Place your .htaccess file in the root document folder of your website (/var/www/html).

 

1. Open .htaccess file

Open .htaccess file in a text editor.


$ sudo vim /var/www/html/.htaccess

 

2. Allow POST requests

Add the following lines to your .htaccess file. Using LimitExcept module, you can limit the type of allowed methods.

Apache 2.2


<LimitExcept POST HEAD>
Order Allow,Deny
Deny from all
</LimitExcept>

 

Apache 2.4+


<LimitExcept POST HEAD>
Require All Denied
</LimitExcept>

 

You can also accomplish the above using RewriteCond.


RewriteEngine On
RewriteCond %{REQUEST_METHOD} !^(POST|HEAD)
RewriteRule .* - [R=405,L]

The above lines will allow only POST and HEAD methods on your web server. If any other method is requested, the user will get a “405 : Method Not Allowed” response.

 

Please Note : The above code will be applied across your entire website. If you want to allow POST methods only in a specific directory such as /uploads/ then create a blank .htaccess file in that folder and add the above lines of code in it.

 

3. Restart Apache web server

Restart Apache web server to apply changes


$ sudo /etc/init.d/apache2 start [Debian or Ubuntu]
# sudo apachectl restart [RHEL, CentOS or Fedora]

 

That’s it! Apache will automatically allow only POST methods on your website.

 

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!