Protecting Website Folders Using .htaccess
The .htaccess file is a powerful Apache configuration tool that allows you to control access to your website’s directories. On ruachost.com, you can use .htaccess to password‑protect folders and prevent unauthorized access.
Why Protect Folders?
Section titled “Why Protect Folders?”- Secure sensitive files (e.g., admin panels, configuration files).
- Restrict access to private content.
- Add an extra layer of authentication beyond application logins.
- Prevent unauthorized users from browsing directories.
How to Protect Folders with .htaccess
Section titled “How to Protect Folders with .htaccess”Step 1: Create a Password File
Section titled “Step 1: Create a Password File”-
Log in via SSH or use a password generator tool.
-
Create a
.htpasswdfile outside the public web root (e.g.,/home/username/.htpasswd). -
Add user credentials in the format:
username:encryptedpasswordYou can generate encrypted passwords using:
htpasswd -c /home/username/.htpasswd user1Step 2: Configure .htaccess
Section titled “Step 2: Configure .htaccess”Place the following code in the .htaccess file inside the folder you want to protect:
# Protect DirectoryAuthName "Restricted Area"AuthType BasicAuthUserFile /home/username/.htpasswdRequire valid-user- AuthName → The message shown in the login dialog box.
- AuthType Basic → Specifies basic authentication.
- AuthUserFile → Path to the
.htpasswdfile. - Require valid-user → Grants access only to users listed in
.htpasswd.
Step 3: Test Access
Section titled “Step 3: Test Access”- Visit the protected folder in your browser.
- A login prompt should appear.
- Enter the username and password you created.
- If correct, access is granted; otherwise, access is denied.
Protecting Subdirectories
Section titled “Protecting Subdirectories”To protect a specific subdirectory (e.g., /members), update the .htaccess file:
# Protect SubdirectoryAuthName "Members Only"AuthType BasicAuthUserFile /home/username/members/.htpasswdRequire valid-user