Sometimes we are required to secure a single URL or a few specific URLs on our site, and all other site URLs keep remain with public access. This is very easy to manage by using directory and file structure in sites. But some frameworks like CakePHP work on routing structure which is different from the directory structure, we can’t secure it on the directory level.
This article will help you secure a specific URL in Apache. For example a site has a secure area like http://example.com/admin/” and we need that only the authorized users or IP addresses can access /admin/ section.
1. Setup IP Based Restriction on Specific URL
First, edit the Apache configuration file and add the below entry in VirtualHost. This will allow /admin URL to 192.168.10.11 or an IP range like 192.168.1.0/24.
<Location /admin> Order deny,allow Deny from all Allow from 192.168.10.11 Allow from 192.168.1.0/24 </Location>
Save the Apache configuration file and restart the apache service using one of the following commands.
sudo systemctl restart httpd
#On RedHat based systems sudo systemctl restart apache2
#On Debian based systems
Let’s try to access your site from any other IP address. Also, check the given IP address in the configuration file.
2. Setup User Authentication on Specific URL
You can also enable a login screen for a specific URL in the Apache webserver. To do this, edit the Apache configuration file and add the below entry in the website VirtualHost section.
<Location /admin> AuthUserFile /var/www/htpasswd/.htpasswd AuthName "Password Protected Area" AuthType Basic Require valid-user </Location>
Now create new htpasswd file using below command and add a new user.
htpasswd -cm /var/www/htpasswd/.htpasswd myuser
OutputNew password: Re-type new password: Adding password for user myuser
Restart the Apache service and access your site URL. It will prompt for login details.
sudo systemctl restart httpd
#On RedHat based systems sudo systemctl restart apache2
#On Debian based systems
Thanks for using this article, I hope this article fulfill your needs. Click here to read more details about apache location directive.
3 Comments
How can we allow certain URLs only, e.g. URLs which starts with /resources , which contains certain word ?
Very helpful and easy to follow. Thanks Chris!
Thanks for the info. Would really help if you mentioned where the apache config file is located.