How to Block POST requests in Apache


block post requests in apache

Sometimes, you may need to block post requests on your website, or in a specific directory. Let us take a look at how to block POST requests in Apache.

 

How to Block POST requests in Apache

Here are the steps to block POST requests in Apache. Before proceeding, please ensure you have enabled .htaccess (mod_rewrite) 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. Block Post Requests

Depending on your use case, add the following lines of code in .htaccess file, to block POST requests.

If you want to block POST requests all over your website,


# deny all POST requests
<IfModule mod_rewrite.c>
RewriteCond %{REQUEST_METHOD} POST
RewriteRule .* - [F,L]
</IfModule>

 

If you want to block POST requests for all except a few known IPs such as localhost or private IPs


# whitelist POST requests
<IfModule mod_rewrite.c>
RewriteCond %{REQUEST_METHOD} POST
RewriteCond %{REMOTE_ADDR} !127.0.0.1
RewriteRule .* - [F,L]
</IfModule>

 

 

If you want to block POST requests all over your website, except a list of specific URL (/contact.php, /login.php),


# whitelist POST requests
<IfModule mod_rewrite.c>
RewriteCond %{REQUEST_METHOD} POST
RewriteCond %{REQUEST_URI} !/contact.php [NC]
RewriteCond %{REQUEST_URI} !/login.php [NC]
RewriteRule .* - [F,L]
</IfModule>

In the above code, please make sure to add a separate RewriteCond for each URL for which you want to allow POST requests.

 

If you want to block POST requests to all URLs in a specific directory (e.g /blog/),


RewriteCond %{REQUEST_METHOD} POST
RewriteCond %{THE_REQUEST} /blog[/?\s] [NC]
RewriteRule ^ - [F,L]

 

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]

 

 

 

 

 

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!