Password protection to Website using htaccess
Password protection to Website using .htaccess is much easier than you ever think. This .htaccess authentication is not only for protection. As a developer, we always have multiple staging and dev environment before production. So authenticating those web servers with .htaccess is recommended. Especially authenticating website with .htaccess will protect your environment from unauthorized access and unwanted SEO crawlings.
The site protected with htaccess will prompt for the authentication whenever it gets the hit.
You can setup this .htaccess authentication within two simple steps.
- Create encrypted password file.
- Configure and map the password file in .htaccess
Creating an encrypted password file
First of all, create a new password file in the document root. This password file will hold all username with the respective password in encrypted format. Each encrypted username and password will be in new line. You can create your own encrypted username and password set without relying on any online tools.
$ htpasswd -nbm username Password
Copy the generated encrypted password to the password file.
“myName:$2y$05$LwGdq19WrsD9w0VzFg0ZuetbL5/bw.S7yyDsjj1rXS13buZuWRBNW”
Note: Give desired random file name to the password file preceded with “.” .
htpasswd command executable is found in the apache/bin if you are using XAMPP in local dev machines.
Configure and map the password file in .htaccess.
We are almost done, the next thing is to add the below mention lines to your .htaccess file in the document root.
AuthType Basic AuthName "My Protected Area" AuthUserFile /absolute/path/to/password/file Require valid-user
Note:
- in addition use the full absolute path in the AuthUserFile . If you use relative path it will result in 500 Server error
- If you use relative path / password file is not accessible will result in 500 Server error
As a result, you can see an authentication popup whenever you hitting the URL freshly.
Know furthermore about the encryption options available.
Know furthermore about the htpasswd attributes