# Protecting website folders using .htaccess

> Password-protect a folder on your website by creating a password file and adding authentication rules to .htaccess.

Source: https://helpcenter.ruachost.com/developers/web-servers/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?

- 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

### Step 1: Create a Password File

1. Log in via SSH or use a password generator tool.
2. Create a `.htpasswd` file outside the public web root (e.g., `/home/username/.htpasswd`).
3. Add user credentials in the format:

   ```
   username:encryptedpassword
   ```

   You can generate encrypted passwords using:

```
htpasswd -c /home/username/.htpasswd user1
```

### Step 2: Configure `.htaccess`

Place the following code in the `.htaccess` file inside the folder you want to protect:

```
# Protect Directory
AuthName "Restricted Area"
AuthType Basic
AuthUserFile /home/username/.htpasswd
Require valid-user
```

- **AuthName** → The message shown in the login dialog box.
- **AuthType Basic** → Specifies basic authentication.
- **AuthUserFile** → Path to the `.htpasswd` file.
- **Require valid-user** → Grants access only to users listed in `.htpasswd`.

### Step 3: Test Access

1. Visit the protected folder in your browser.
2. A login prompt should appear.
3. Enter the username and password you created.
4. If correct, access is granted; otherwise, access is denied.

## Protecting Subdirectories

To protect a specific subdirectory (e.g., `/members`), update the `.htaccess` file:

```
# Protect Subdirectory
AuthName "Members Only"
AuthType Basic
AuthUserFile /home/username/members/.htpasswd
Require valid-user
```

> **Important Notes:**
- Place `.htpasswd` outside `public_html` for security.
- Ensure correct file permissions (e.g., `644` for `.htaccess`, `640` for `.htpasswd`).
- Misconfigured rules may cause **500 Internal Server Errors**.
- Always back up `.htaccess` before editing.
