Most webpages use WordPress. However, the “admin”-area of WordPress is one of the biggest gateways to gain control over your website. Therefore, some security safeguards are necessary. In this article we focus on servers-side admin-area-protection with .htaccess and .htpasswd.
Source: GIPHY, Pluralsight
Our goal is to protect access to the admin area on server level by means of a user-password-query. I configure an Apache webserver with code snippets for the files .htaccess and .htpasswd.
Create and edit the “.htpasswd”-file
Log in with the credentials of your webhoster and create a new file named “.htpasswd” in the root directory of your WordPress website. In this document we store the hashed credentials.
To fill the file with content, we use the “htpasswd generator by Aspirine.org“. The easist usage of the tool is to click on “Generate password” (10 characters) in the box “1. Users and passwords”.
Model the settings to suit your individual security risk requirements. The output looks like this:
Simone B25,{2&/ye
Martha \?k%c8RRfm
After that, you click on “Generate htpasswd content” and see content in the box “2. Generated htpasswd file”. This content is copied to the “.htpasswd” file and should look similiar to this code:
Simone:$2y$11$Oxp5jv19xTdiv.u72TzaHuvoIlPLmlcU2jQT6Bl8nT84qocZhvHfm
Martha:$2y$11$mDPIIUCMDk11xzFKsJUFY.CCVbVRiNebQ1WjJdkbribYIxu/bdkAq
Create and edit the “.htaccess”-file
In most cases there should be already a “.htaccess”-file in the root directory. If not, just quickly create a file with the name “.htaccess”. In case of an Apache webserver (> Apache 2.4) copy the following code snippet and paste it behind the term “#END WordPress” into the “.htaccess”-file.
# Apache 2.4 or newer
# Auth protect wp-login.php
<Files wp-login.php>
AuthType Basic
AuthName "Restricted Admin-Area"
AuthUserFile [Where is the .htpasswd-file?]
Require valid-user
</Files>
# Deny access to important files
<FilesMatch "(\.htaccess|\.htpasswd)">
Require all denied
</FilesMatch>
A trouble-spot is to adjust the exact path of the password file “.htpasswd” under AuthUserFile (Where is the .htpasswd-file?). Luckily, you can easily use the PHP-Snippet from Hostingcanada. Create another file in the root directory with the name “fullpath.php” and edit it with this code:
<?php $dir = dirname(__FILE__); echo "<p>Full path to this dir: " . $dir . "</p>"; echo "<p>Full path to a .htpasswd file in this dir: " . $dir . "/.htpasswd" . "</p>"; ?>
Now you point your browser to “http://www.[ENTER DOMAIN NAME]/fullpath.php”. There you find the adress (“/[place of the .htpasswd-file]”) that you need to enter after the AuthUserFile.
Full path to this dir: /[...]
Full path to a .htpasswd file in this dir: /[...]
Success: Second passphrase layer in WordPress
If you have done everything correct: Congratulation your webpage has a second username-password layer. A technical brake on every login. More coffee joy and less joy for attackers.
¯ \ _(ツ)_/¯