The htaccess file (hypertext access file) is a powerful tool that allows us to make configurations at the directory and subdirectory level and controls how a web server responds to incoming requests.
The main use cases of .htaccess file are:
- Setting up URL rewriting rules.
- Protecting web pages with passwords.
- Displaying custom error pages.
1) Protecting web pages with password
- Open the default Apache configuration file. Use the command that follows.
sudo vi /etc/httpd/conf/httpd.conf
- Search directory block for /var/www/html and change AllowOverride to AuthConfig from none.

- Create .htaccess file in /var/www/html directory.
sudo vi /var/www/html/.htaccess
- In the file, paste the following code.
AuthType Basic
AuthName "Restricted Content"
AuthUserFile /etc/httpd/.htpasswd
Require valid-user
- Restart Apache service.
sudo systemctl restart httpd
- Create .htpasswd file.
sudo htpasswd -c /etc/apache2/.htpasswd username
- Enter password when prompted.
- We are all set up. Now go to your browser and access your site, you will see a prompt for username and password.

2) Setting up URL rewriting rules
-
- htaccess file can be used to transfer requests from one directory to other. In the file, paste the following code.
Options +FollowSymLinks RewriteEngine On RewriteRule ^folder1.*$ http://example.com/folder2/ [R=301,L]
- Copy the following code, if you want to stop traffic from being redirected from a particular site to yours.
RewriteEngine on
# Options +FollowSymlinks
RewriteCond %{HTTP_REFERER} blockedsite\.com [NC]
RewriteRule .* - [F]
3) Setting up custom error page
- Add the following code in file.
ErrorDocument 404 /errorpage.html
- Make a custom error html page in the directory with htaccess file.
Please contact our technical consultants if you have anything related to SRE Management, Cloud infrastructure and DevOps Management. We can also help to hire remote fullStack developer.
