Password protect a webpage

If you want a simple authentication method for a private page, the best way to do this on Leprd (and other apache webhosts) by creating htaccess and htpasswd files.

Create the password file

Go to the directory (folder) of the pages you want to protect. Create a file and name it .htpasswd

We want to generate a secure credentials not stored in plaintext. Use this Htpasswd Generator to enter your desired username and password, and then copy the results to your clipboard.

It should look something like this:

username:$jgJs$kfkg$/gkd&H/4$4
Code language: PHP (php)

If you just want to test it out, you don’t need to encrypt your password. Also, I noticed some password encryption generators just don’t work. To set a plaintext password just use this format:

username:password
Code language: CSS (css)

In that file, paste the credentials from your clipboard.

Create the .htaccess file

In the same directory, create a file and name it .htaccess

What you will paste in your .htaccess file will vary depending on what you want to protect.

To protect a single file (by filename)

<Files admin.php> AuthName "Dialog prompt" AuthType Basic AuthUserFile .htpasswd Require valid-user </Files>
Code language: HTML, XML (xml)

To protect multiple files (by filenames)

<FilesMatch "^(admin|staff).php$"> AuthName "Dialog prompt" AuthType Basic AuthUserFile .htpasswd Require valid-user </FilesMatch>
Code language: PHP (php)

To protect a directory (protects entire directory)

AuthName "Dialog prompt" AuthType Basic AuthUserFile .htpasswd Require valid-user
Code language: PHP (php)

Then, visit your page and test it out! Once you put in your password, your browser will remember it. You can test if authentication is still working by visiting the page in a private browsing mode.



Hey, thanks for reading! If you have any questions, you can leave me a comment and I always try to reply.

If you have any suggestions on how I can improve this article, please let me know!

This website is not monetized in any way. It purely exists to help others on their web-building journey. However, if you have the means to donate toward my server costs, I have a ko-fi account where I accept tips.

Leave a Comment