Skip to main content

Protect wp-admin by Basic Auth

Protect wp-admin by Basic Auth

You have to protect the wp-admin / wp-login.php at least by the baisc-auth if you do not want to do it using Cloduflare

Here is the steps to Protect it

  • You have to know the full path of your website root, you can use getcwd() or __DIR__
  • Create a directory outside the root and name it to something like (.htpasswds) this will allow to save all password withouot accessing them from the website root
  • lets assume that your root of the website is /var/www/.htpasswds
  • in that case the htpasswds will be  /var/www/public_html
  • in Your .htaccess file in the website root you have to add this code  ({website domain is optional only to organzie the passwords and you can choose any thing you want})
    <FilesMatch "wp-login.php">
        AuthName "Authorized Only"
        AuthType Basic
        AuthUserFile /var/www/.htpasswds/{website domain}/.htpasswd
        require valid-user
  • now in .htpasswd file  you can add your access as you want , follow one of the below articles to create a username and password 


to Create a password by SSH command follow the below Steps

Create the Password File
We now have access to the htpasswd command. We can use this to create a password file that Apache can use to authenticate users. We will create a hidden file for this purpose called .htpasswd within our /etc/apache2 configuration directory.

The first time we use this utility, we need to add the -c option to create the specified file. We specify a username (sammy in this example) at the end of the command to create a new entry within the file:

sudo htpasswd -c /etc/apache2/.htpasswd another_user1

You will be asked to supply and confirm a password for the user.

Leave out the -c argument for any additional users you wish to add:

sudo htpasswd /etc/apache2/.htpasswd another_user2

If we view the contents of the file, we can see the username and the encrypted password for each record:

cat /etc/apache2/.htpasswd




Another way is to use cookies to protect wp-admin/wp-login.php

the main idea here is to check if the cookies is exist then continue to the backend , if not then it will be redirected to the homepage

in the .htaccess file add these two parts 

<FilesMatch "wp-admin">
RewriteEngine On
RewriteCond %{HTTP_COOKIE} !itweb-wp-login=2917998723; [NC]
RewriteRule ^ [NC,L]

<FilesMatch "wp-login.php">
RewriteEngine On
RewriteCond %{HTTP_COOKIE} !itweb-wp-login=2917998723; [NC]
RewriteRule ^[NC,L]


and create new PHP file to set this cookies manually , lets call it set_cookies.php and add this code 


setcookie("itweb-wp-login", 2917998723);
header("Location: wp-login.php");



    How To Set Up Password Authentication with Apache on Ubuntu 14.04 | DigitalOcean

    How To Change WordPress Login URL Without Plugin: 3 Methods (