How to Block URLs using .htaccess


how to block url in htaccess

Sometimes, you may need to block specific URLs, especially if they contain sensitive information, from external traffic. .htaccess file allows you to block URLs in Apache web server without accessing its config file. Let us take a look at how to block URLs using .htaccess.

 

How to Block URLs using .htaccess

Here’s how to block URLs using .htaccess file in Apache. Before you proceed, please ensure that you have enabled mod_rewrite (.htaccess) in your Apache web server. Here are the steps to do it:

 

1. Open .htaccess file

Open .htaccess file using a text editor. It is generally located at /var/www/html.


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

 

2. Block URL

Let’s say you want to block a specific URL /admin/login.php, then add the following RewriteRule in .htaccess


RewriteEngine On
RewriteCond %{REQUEST_URI} ^/admin/login.php
RewriteRule ^(.*)$ - [F,L]

 

This will block the specific URL.

 

Let’s say you want to block all URLs in a directory /admin/, then you can do that with RedirectMatch statement.

RedirectMatch 403 ^/admin/?$

This will only block the directory but not the files and subdirectories in it. If you want to block them too, then use .* instead of ? as shown below

RedirectMatch 403 ^/admin/.*$

 

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!