How to password-protect your entire WordPress site with .htaccess
Sometimes the whole site has to be hidden from prying eyes, for example during development or on a staging server. The quickest and most reliable way is HTTP Basic Authentication with .htpasswd and .htaccess: the server asks for a login before WordPress even starts, and no plugin is needed.
Problem: A site under development or on a staging server must be closed to everyone (search engines, clients, random visitors) except the people who have a password.
Step 1. Connect to the server
ssh user_name@host-name.com
Step 2. Create the .htpasswd file
Replace user_name with the login you want, then enter the password when prompted:
htpasswd -c /home/user_name/.htpasswd user_name
The -c flag creates a new file; leave it out when adding more users, otherwise the file is overwritten. Keep .htpasswd outside the web root if you can (here it’s in the home folder), so it can never be downloaded.
Step 3. Add the rules to .htaccess
Open the .htaccess file in the web root (create it if it doesn’t exist):
vi .htaccess
Add the following, with the absolute path to your .htpasswd in AuthUserFile:
# Hide version control folders and README files
RedirectMatch 404 /\.(svn|git|hg|bzr|cvs)(/|$)
RedirectMatch 404 /README.md$
# Password protection
AuthName "Authorization required"
AuthType Basic
AuthUserFile /home/user_name/.htpasswd
Require valid-user
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
Every visitor now sees the browser’s login dialog before any page of the site.
Let your own IP in without a password
On Apache 2.4, list the addresses in a <RequireAny> block instead of the single Require valid-user line. A visitor passes if any of the conditions is true:
<RequireAny>
Require ip 203.0.113.10
Require valid-user
</RequireAny>
On old Apache 2.2 servers the same is done with Order deny,allow, Deny from all, Allow from 203.0.113.10 and Satisfy Any. Don’t mix the two syntaxes in one file.
Notes
AuthUserFileneeds an absolute server path, not a URL. If you’re not sure of it, runpwdin the folder with the file.- The
HTTP_AUTHORIZATIONrewrite rule passes the login header to PHP. Some hosts don’t pass it by default, which breaks plugins that use their own HTTP authentication. - Remove the protection when the site goes live, or search engines will see only a 401 error.