Protecting your website with a password is one of the simplest and most effective ways to limit access to sensitive content. Whether you’re restricting access to a development site, admin area, or staging environment, the .htaccess + .htpasswd method is a reliable solution for Apache servers. At the web‑server level, this approach not only safeguards user‑facing pages but also server services such as management panels (phpMyAdmin, cPanel), server status pages (/server-status), metrics, and any other virtual‑host directories. This guide will show you how to implement basic HTTP authentication using .htaccess and .htpasswd files.
The .htpasswd file stores the encrypted usernames and passwords.
You can generate a password hash using the following terminal command:
htpasswd -c /home/yourusername/.htpasswd yourusername
Replace /home/yourusername/ with your actual user path and yourusername with the username you want to require for access.
Edit or create a .htaccess file in the directory you want to protect and add:
AuthType Basic
AuthName "Restricted Area"
AuthUserFile /home/yourusername/.htpasswd
Require valid-user
Don’t forget: The .htaccess file must be placed in the folder you want to protect.
сOpen the URL of your protected directory in a browser.
If everything is set up correctly, you’ll see a login popup asking for your credentials.
Using .htaccess to password-protect your site is a quick way to add an additional layer of security without complex development. It’s ideal for staging sites, admin panels, and temporary content.