Password Protect WordPress Staging in .htaccess (REST API Safe)

by Fahim Mahmud Chisti

You want to password protect a WordPress staging site in .htaccess, but plain HTTP Basic Auth also blocks everything that calls the REST API without your browser’s password. Webhooks stop arriving, WP-Cron and Site Health loopback checks fail, and API clients cannot log in, all silently, because Apache rejects the requests before WordPress loads. This guide locks the site down while letting /wp-json/, cron and webhooks through.

Quick answer: Add Basic Auth in .htaccess, flag /wp-json/ and wp-cron.php with SetEnvIf, and use a RequireAny block that accepts either the flag or a valid password.

  1. Create a .htpasswd file outside the web root with htpasswd -c.
  2. At the top of .htaccess, add SetEnvIf lines for /wp-json/ and /wp-cron.php.
  3. Add AuthType Basic, AuthUserFile and a RequireAny block with Require env allow_rest, Require env REDIRECT_allow_rest and Require valid-user.
  4. Keep the Authorization header rule in the WordPress block.
  5. Test with curl: the homepage should return 401 and /wp-json/ should return 200.
In this guide
  1. Before You Start
  2. Why Basic Auth Breaks the WordPress REST API
  3. Step 1: Create the .htpasswd Password File
  4. Step 2: Add Basic Auth to .htaccess and Exempt wp-json
  5. Step 3: Cover Plain-Permalink REST Calls (?rest_route=)
  6. Step 4: Make Sure PHP Receives the Authorization Header
  7. Step 5: Test the Setup with curl
  8. If It Doesn’t Work
  9. Alternative: Allow Your IP Addresses Instead
  10. Keep WP-Cron and Background Tasks Running
  11. Complete .htaccess File
  12. Frequently Asked Questions
  13. Next Steps
Close-up of a rack-mounted hosting server running Apache security configurations

Before You Start

  • Server type: Apache 2.4, or a server such as LiteSpeed that reads .htaccess files (most shared hosting). If your staging site runs on Nginx, follow the guide to password protect WordPress staging on Nginx instead.
  • Access: SSH to run htpasswd, and file access (SFTP, SSH or your host’s file manager) to the staging site’s .htaccess.
  • A staging copy: on Hostinger you can create one in hPanel first; see how to set up a WordPress staging site in Hostinger hPanel.
  • Time: about 15 minutes.
  • Backup: download a copy of the current .htaccess. A typo in it returns a 500 error for the whole staging site.

Why Basic Auth Breaks the WordPress REST API

Apache’s Basic Auth (the mod_auth_basic module) asks every request for an Authorization: Basic header before PHP or WordPress runs.

WordPress relies heavily on the REST API. The block editor (Gutenberg) talks to /wp-json/wp/v2/ to autosave drafts, fill category and tag pickers, and render previews. Your own browser copes with this: once you have entered the Basic Auth password, it sends it with same-origin fetch() calls automatically.

The trouble is everything that is not your browser. Requests WordPress sends to itself (WP-Cron, Site Health’s REST API and loopback tests, some plugins) carry no credentials and get Apache’s HTML 401 page instead of JSON. API clients hit a second problem: a request has only one Authorization header, so it cannot carry the staging password and a WordPress Application Password at the same time.

Server-to-server calls fail the same way. Stripe webhooks or remote publishing tools receive a hard 401 from Apache.

Step 1: Create the .htpasswd Password File

Apache reads usernames and hashed passwords from a .htpasswd file. Keep it outside the public web root (above public_html or html) so nobody can download it in a browser.

Connect over SSH and move to a folder one level above the web root, such as /home/username/ or /var/www/. Then create the file with your first user:

cd /home/u123456789/
htpasswd -c .htpasswd staginguser

You are asked to enter the password twice, and htpasswd confirms that it added the user. The -c flag creates a new file. To add a second user later, leave out -c, or you will overwrite the existing users:

htpasswd .htpasswd seconddeveloper

Set the file permissions so the web server can read it. On shared hosting that usually means 644, which is one more reason to keep the file outside the web root; on your own server, prefer 640 with the web server’s group (chown root:www-data):

chmod 644 /home/u123456789/.htpasswd

Step 2: Add Basic Auth to .htaccess and Exempt wp-json

Open the .htaccess file in the staging site’s root folder (next to wp-config.php). The method uses Apache’s SetEnvIf directive to flag requests for the REST API or cron, then lets flagged requests skip the password.

Paste this block at the very top of .htaccess, above # BEGIN WordPress, and change the AuthUserFile path to the full path of your .htpasswd file:

# Flag REST API and cron requests so they can skip Basic Auth
SetEnvIf Request_URI "^/wp-json/" allow_rest=1
SetEnvIf Request_URI "^/wp-cron.php$" allow_rest=1

AuthType Basic
AuthName "Staging Environment - Private Access"
AuthUserFile /home/u123456789/.htpasswd

# Grant access if the request is flagged OR the visitor has valid credentials
<RequireAny>
    Require env allow_rest
    Require env REDIRECT_allow_rest
    Require valid-user
</RequireAny>

How it works: if the request path begins with /wp-json/ or is exactly /wp-cron.php, Apache sets an internal variable, allow_rest=1. The RequireAny block grants access if that variable is set or the visitor enters valid credentials. The REDIRECT_allow_rest line is not optional: WordPress’s rewrite rules internally redirect /wp-json/ requests to index.php, and after that redirect Apache renames the variable with a REDIRECT_ prefix before it checks access again. These are Apache 2.4 directives; if your host runs LiteSpeed, use the curl tests in Step 5 to confirm they are honored.

Save the file and open the staging homepage in a private window. You should see a password prompt.

Not every staging site uses pretty permalinks. If yours uses plain permalinks, or a plugin calls the REST API with a query string like ?rest_route=/, the SetEnvIf Request_URI rule misses it, because Request_URI never includes the query string.

A mod_rewrite rule cannot fix this: in .htaccess, rewrite rules run after Apache has already checked access. Use SetEnvIfExpr instead, limited to requests for the site root or index.php, so the parameter cannot be added to other URLs to skip the password. Add this below the two SetEnvIf lines:

# Plain-permalink REST calls (/?rest_route=/...)
SetEnvIfExpr "%{REQUEST_URI} =~ m#^/(index[.]php)?$# && %{QUERY_STRING} =~ /(^|&)rest_route=/" allow_rest=1

If your staging site lives in a subfolder of another site, watch out for the parent folder’s .htaccess: Apache applies its rules to the subfolder too.

Step 4: Make Sure PHP Receives the Authorization Header

This one is easy to miss on Apache with PHP-FPM or FastCGI: by default, Apache does not pass the Authorization header on to PHP.

Basic Auth itself still works, but WordPress’s own authentication (Application Passwords, added in WordPress 5.6, or JWT tokens for headless setups) breaks, because PHP sees an empty $_SERVER['HTTP_AUTHORIZATION'].

The official WordPress REST API Authentication Documentation explains why the header is needed. WordPress has included a rule for this in its default .htaccess block since version 5.6. If yours is missing it, add the rule:

<IfModule mod_rewrite.c>
RewriteEngine On
# Pass the Authorization header down to PHP
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
</IfModule>

With that in place, and with /wp-json/ exempt from Basic Auth as above, test scripts and headless clients can authenticate with WordPress Application Passwords through the REST API.

Step 5: Test the Setup with curl

Do not test this only in your normal browser. Browsers remember Basic Auth credentials for the whole session, which hides mistakes. Run these three checks from your local terminal.

Check 1: the front end without credentials. It should return 401 Unauthorized:

curl -I https://staging.example.com/

Check 2: the front end with credentials. It should return 200 OK:

curl -I -u staginguser:yourpassword https://staging.example.com/

Check 3: the REST API without credentials. It should return 200 OK; without -I, it prints the API’s JSON index:

curl -I https://staging.example.com/wp-json/

If check 1 returns 401 while checks 2 and 3 return 200, the rules work. The front end stays locked to crawlers and visitors, while the block editor and background integrations keep running.

If It Doesn’t Work

  • The whole site shows 500 Internal Server Error. Apache could not read a directive or the password file. Check that AuthUserFile is the full path to .htpasswd and that the file is readable, then check your host’s error log. Restore your backup .htaccess if you need the site back immediately.
  • The password prompt keeps coming back. The username or password does not match the file. Recreate the user with htpasswd and try again in a fresh private window.
  • Check 3 returns 401. The Require env REDIRECT_allow_rest line is missing, a parent folder’s .htaccess overrides yours, or your server handles these directives differently. Use the IP allowlist below instead.
  • Scheduled posts stop publishing. The wp-cron.php line is missing or misspelled. See the WP-Cron section below.

Alternative: Allow Your IP Addresses Instead

If opening /wp-json/ to the public on a staging site makes you uneasy, you can let in specific developer IPs or webhook IP ranges instead. This stops scrapers from reading public user lists or categories from the open API.

This block lets your office or home IP in without a password, while everyone else must log in:

AuthType Basic
AuthName "Private Developer Staging"
AuthUserFile /home/u123456789/.htpasswd

<RequireAny>
    # Allow developer static IP
    Require ip 203.0.113.45
    # Allow local network or office subnet
    Require ip 198.51.100.0/24
    # Allow anyone with credentials
    Require valid-user
</RequireAny>

If your team works from changing home IPs, keeping the list up to date quickly becomes a chore, so the path-based bypass is usually more practical. Unauthenticated REST requests still respect WordPress permissions: visitors can only read content that would be public on the front end anyway.

Keep WP-Cron and Background Tasks Running

Staging sites often need to run scheduled actions, automatic imports or WooCommerce syncs. If wp-cron.php sits behind Basic Auth, those jobs stop without any error.

Because the main block includes SetEnvIf Request_URI "^/wp-cron.php$" allow_rest=1, requests to wp-cron.php already pass without credentials, including WordPress’s own loopback cron requests.

If you have replaced WP-Cron with a system cron job and removed that exemption, either run wp-cron.php directly with the PHP command line, or send your Basic Auth credentials with curl. Add a line like this to the server’s crontab (crontab -e over SSH, or your host’s cron job screen):

# Trigger cron using HTTP Basic Auth credentials
*/10 * * * * curl -s -u staginguser:yourpassword "https://staging.example.com/wp-cron.php?doing_wp_cron" > /dev/null 2>&1

For the full setup on Hostinger, see how to disable WP-Cron and set up a real cron job.

Complete .htaccess File

Here is the whole .htaccess file with every piece in place. Use it as the staging site’s .htaccess, update the .htpasswd path, and keep any other blocks your plugins added (for example cache plugin rules):

# Flag REST API and cron requests so they can skip Basic Auth
SetEnvIf Request_URI "^/wp-json/" allow_rest=1
SetEnvIf Request_URI "^/wp-cron.php$" allow_rest=1
# Plain-permalink REST calls (/?rest_route=/...)
SetEnvIfExpr "%{REQUEST_URI} =~ m#^/(index[.]php)?$# && %{QUERY_STRING} =~ /(^|&)rest_route=/" allow_rest=1

# Configure Basic Authentication
AuthType Basic
AuthName "Staging Area"
AuthUserFile /home/u123456789/.htpasswd

<RequireAny>
    Require env allow_rest
    Require env REDIRECT_allow_rest
    Require valid-user
</RequireAny>

# 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

For details on how RequireAny combines conditions, see the official Apache HTTP Server 2.4 documentation.

Frequently Asked Questions

Why does Gutenberg show “Updating failed” when I save a post?

Because a REST request came back as something other than JSON. Gutenberg saves through /wp-json/wp/v2/. Behind Basic Auth your browser normally sends the password with those calls, so check the Network tab for the real status first. If the calls get Apache’s 401 page (for example because www and non-www differ), exempting /wp-json/ fixes it.

Does exempting /wp-json/ expose my staging database to hackers?

No. The REST API runs its own permission checks. Editing posts, viewing drafts or changing settings needs a valid WordPress login cookie or an Application Password. A visitor without one can only see content that would already be public on the front end.

Can I password protect only wp-login.php instead?

Yes. To protect just the login screen, wrap the auth lines in a <Files wp-login.php> block. That leaves the front end visible to search engines, though, so for a staging site you would also need a noindex header.

What happens if I push this .htaccess file from staging to production?

Your live site will ask every visitor for a username and password. Exclude .htaccess from automated deployments, or have your deploy process swap in the production version on release.

Next Steps

  1. Run the three curl checks again after any plugin or permalink change.
  2. Share the staging password through a password manager, not chat or email.
  3. Before you push staging to live, remove the Basic Auth block from the .htaccess that goes to production.
all_in_one_marketing_tool