Password Protect WordPress Staging on Nginx with HTTP Basic Auth

by Fahim Mahmud Chisti

A staging site that anyone can open gets crawled, indexed and copied, and the “Discourage search engines” box in WordPress does not stop that: scrapers ignore robots.txt. The reliable fix is to password protect the WordPress staging site on Nginx with HTTP Basic Auth, so every visitor must log in before PHP or MySQL do any work. This guide sets that up and keeps SSL renewals, webhooks and WP-Cron working.

Quick answer: Create a password file with htpasswd, add auth_basic and auth_basic_user_file to the staging server block, exempt the Let’s Encrypt challenge path, then confirm with curl that visitors get a 401.

  1. Install apache2-utils and run sudo htpasswd -B -c /etc/nginx/.htpasswd_staging stagingdev.
  2. Add the two auth_basic lines inside the server block, not only in location /.
  3. Turn auth_basic off for /.well-known/acme-challenge/.
  4. Add exceptions for webhooks or admin-ajax.php only if you need them.
  5. Run sudo nginx -t, reload Nginx and check that curl -I returns 401.
In this guide
  1. Before You Start
  2. Why Nginx Basic Auth Beats a Password Plugin
  3. Step 1: Install htpasswd and Create the Password File
  4. Step 2: Add Basic Auth to the Staging Server Block
  5. Step 3: Let Let’s Encrypt Through (ACME Challenges)
  6. Step 4: Keep admin-ajax.php and Webhooks Working
  7. Step 5: Understand the Authorization Header Limit
  8. Step 6: Skip the Password for Your Own IP Addresses
  9. Step 7: Test with curl and Check the Logs
  10. If It Doesn’t Work
  11. Frequently Asked Questions
  12. Next Steps
Close-up of server hardware running an Nginx web server environment

Before You Start

  • Server type: this guide is for Nginx, where you can edit the site’s config. If your staging site runs on Apache or LiteSpeed (most shared hosting, including Hostinger’s shared plans), use the guide to password protect WordPress staging in .htaccess instead.
  • Access: SSH with sudo on the server, and a staging site already running on its own domain or subdomain with HTTPS.
  • Time: about 15–20 minutes.
  • Backup: copy the site’s Nginx file before editing, and always run sudo nginx -t before a reload so a typo cannot take the server down.

Why Nginx Basic Auth Beats a Password Plugin

Many staging guides suggest a maintenance-mode or password-protection plugin. That works on small sites, but it has two weaknesses.

First, every unauthenticated request still loads WordPress. PHP starts, connects to MySQL and runs queries just to show a login form. When a crawler hits your staging domain, that load adds up quickly.

Second, page caches and CDNs can cache the plugin’s login screen, or worse, cache a logged-in page and show it to anonymous visitors.

Nginx handles Basic Auth itself through the ngx_http_auth_basic_module. A visitor without the password gets a 401 Authorization Required response before the request ever reaches PHP.

Step 1: Install htpasswd and Create the Password File

Nginx has no tool of its own for creating passwords, so you use htpasswd. On Debian or Ubuntu it comes in the apache2-utils package; on RHEL, AlmaLinux or Rocky Linux it is in httpd-tools.

Connect to the server over SSH and install the package for your system:

# On Ubuntu/Debian
sudo apt update
sudo apt install -y apache2-utils

# On RHEL/AlmaLinux
sudo dnf install -y httpd-tools

Now create the password file. Do not put it in your web root (like /var/www/staging.example.com): if the Nginx config ever breaks, visitors could download your password hashes. Keep it in /etc/nginx/ instead:

sudo htpasswd -B -c /etc/nginx/.htpasswd_staging stagingdev

The -B flag uses bcrypt hashing instead of the weaker default (Apache’s MD5 variant). Nginx checks bcrypt hashes through the system’s crypt library, which supports them on current Ubuntu and Debian releases; if logins fail with a crypt_r() failed error in the Nginx log, regenerate the file without -B. The -c flag creates the file. You are asked for the password twice, and htpasswd confirms it added the user. To add a teammate later, run the same command without -c, or you will wipe out the existing users.

Restrict the file so only root and the Nginx worker process can read it:

sudo chown root:www-data /etc/nginx/.htpasswd_staging
sudo chmod 640 /etc/nginx/.htpasswd_staging

Step 2: Add Basic Auth to the Staging Server Block

Open your staging site’s Nginx config. If you set up the staging subdomain with our guide to route subdomains to different servers in Namecheap DNS, the server block is usually in /etc/nginx/sites-available/staging.example.com or /etc/nginx/conf.d/staging.conf:

sudo nano /etc/nginx/sites-available/staging.example.com

Add the auth_basic and auth_basic_user_file lines inside the main server block. Do not put them only in location /: direct requests to PHP files such as /wp-login.php are handled by the PHP location and would stay unprotected. Here is a complete baseline for PHP 8.2 and WordPress permalinks; change the domain, paths and PHP socket to match your server:

server {
    listen 443 ssl http2;
    server_name staging.example.com;
    root /var/www/staging.example.com;
    index index.php index.html;

    # SSL configuration (Certbot paths)
    ssl_certificate /etc/letsencrypt/live/staging.example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/staging.example.com/privkey.pem;

    # HTTP Basic Auth global lockdown
    auth_basic "Restricted Staging Environment";
    auth_basic_user_file /etc/nginx/.htpasswd_staging;

    location / {
        try_files $uri $uri/ /index.php?$args;
    }

    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/run/php/php8.2-fpm.sock;
    }

    # Deny hidden files ([.] matches a literal dot)
    location ~ /[.] {
        deny all;
    }
}

Test the syntax before reloading, so a missing semicolon cannot take your server offline:

sudo nginx -t

If you see syntax is ok and test is successful, reload Nginx:

sudo systemctl reload nginx

Open the staging URL in a private browser window. You should get a login popup before any WordPress page appears.

Step 3: Let Let’s Encrypt Through (ACME Challenges)

This is the first trap that breaks staging setups: automatic SSL renewal. Certbot proves you own the domain with an HTTP-01 challenge, a request to /.well-known/acme-challenge/ over plain HTTP on port 80.

If Basic Auth blocks that request, renewal fails with a 401 and the certificate eventually expires without warning. For the full diagnosis, see how to fix Certbot SSL auto-renewal failures on Nginx.

Turn auth_basic off for the challenge folder in both your HTTP (port 80) and HTTPS (port 443) server blocks:

location ^~ /.well-known/acme-challenge/ {
    auth_basic off;
    allow all;
    root /var/www/html;
}

The ^~ modifier tells Nginx: if this prefix matches, stop checking regular-expression locations. That also keeps the hidden-files rule from Step 2 from blocking .well-known. Set root to the folder Certbot writes its challenge files to. After reloading, run sudo certbot renew --dry-run; it should report that the simulated renewal succeeded.

Step 4: Keep admin-ajax.php and Webhooks Working

If you test webhooks from Stripe or PayPal, run a headless front end, or use front-end AJAX forms, Basic Auth can cause silent failures.

Your own browser sends the Basic Auth credentials with its AJAX requests to /wp-admin/admin-ajax.php, so those usually work. Webhooks from outside services do not have the password and fail with a 401. The same applies to the WordPress REST API if an external service pushes test data into staging.

If external services must reach admin-ajax.php or a webhook route while everything else stays locked, add exception locations inside the server block:

# Let external services reach admin-ajax.php without the auth prompt
location = /wp-admin/admin-ajax.php {
    auth_basic off;
    allow all;
    include snippets/fastcgi-php.conf;
    fastcgi_pass unix:/run/php/php8.2-fpm.sock;
}

# Optional: expose one REST API route for an external webhook
location ^~ /wp-json/my-custom-plugin/v1/webhook {
    auth_basic off;
    allow all;
    rewrite ^ /index.php break;
    include snippets/fastcgi-php.conf;
    fastcgi_pass unix:/run/php/php8.2-fpm.sock;
}

Both exceptions pass the request to PHP-FPM themselves, because Nginx does not combine location blocks: once it picks one, it ignores the instructions in the others. That is also why the REST route rewrites to /index.php with break instead of using try_files. A try_files fallback jumps into the regular PHP location, where the server-level auth_basic applies again and the webhook still gets a 401. The allow all; lines only matter once you add the IP allowlist from Step 6.

To check an exception, run curl -I against that exact URL without credentials. It should return a status from WordPress, not a 401.

Step 5: Understand the Authorization Header Limit

WordPress and many plugins read the Authorization header for Application Passwords or OAuth tokens. Nginx already forwards every request header to PHP-FPM, so $_SERVER['HTTP_AUTHORIZATION'] is filled in without any extra fastcgi_param line.

The real limit is that a request can carry only one Authorization header. While Basic Auth protects the site, that header holds the staging password, so an API client cannot also send a WordPress Application Password or bearer token in it. If your workflow relies on authenticated REST API calls, exempt those routes as in Step 4, or allow the client’s IP address as in Step 6.

Step 6: Skip the Password for Your Own IP Addresses

Typing the staging password all day while you debug gets old fast. You can let your office or home IP straight in while still asking everyone else for the password.

This uses satisfy any;, which grants access if the visitor matches the IP allowlist or enters valid credentials. Put it at the server level, next to the auth_basic lines, not inside location /: WordPress requests end up in the PHP location, which does not inherit rules from a sibling location.

# Inside the server {} block, next to the auth_basic lines
satisfy any;

# Whitelist developer office IPs
allow 203.0.113.45;
allow 198.51.100.22;
deny all;

auth_basic "Restricted Staging Environment";
auth_basic_user_file /etc/nginx/.htpasswd_staging;

If Nginx sits behind Cloudflare or another CDN, it sees the proxy’s IP instead of yours. Restore the real visitor address with ngx_http_realip_module (set_real_ip_from and real_ip_header) before relying on an IP allowlist.

Step 7: Test with curl and Check the Logs

Do not rely on your browser to test this. Browsers remember Basic Auth credentials for the whole session, which hides mistakes.

From your local terminal, check that a request without credentials gets a 401 and a WWW-Authenticate header:

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

The response headers should look like this:

HTTP/2 401
server: nginx
content-type: text/html
www-authenticate: Basic realm="Restricted Staging Environment"
content-length: 179

Now test with your credentials using the -u flag:

curl -I -u stagingdev:YourSecurePassword https://staging.example.com

You should get HTTP/2 200 straight away.

To watch failed logins in real time, follow the Nginx error log on the server while you try to log in:

sudo tail -f /var/log/nginx/error.log

A mistyped password shows up as an entry containing user "stagingdev": password mismatch. Press Ctrl + C to stop following the log.

If It Doesn’t Work

  • HTTP 500 Internal Server Error: check /var/log/nginx/error.log. Usually the Nginx worker (often www-data) cannot read /etc/nginx/.htpasswd_staging. Fix it with sudo chmod 640 /etc/nginx/.htpasswd_staging and sudo chown root:www-data /etc/nginx/.htpasswd_staging.
  • Repeated password prompts on CSS, JavaScript or images: look for a separate block like location ~* \.(css|js|png|jpg)$. Static-file locations must not have their own, conflicting access rules.
  • The homepage asks for a password, but /wp-login.php does not: the auth_basic lines are inside location / only. Move them up to the server block.
  • Certbot renewal fails with 401: the ACME exception from Step 3 is missing from the port 80 server block.
  • Two login screens: a browser popup, then the normal wp-login.php page. That is expected. Basic Auth is the outer gate; your WordPress account is the inner one.

Frequently Asked Questions

Can I use HTTP Basic Auth on a subfolder staging site?

Yes. If staging lives at example.com/staging/ rather than on its own subdomain, put the auth_basic lines inside a location ^~ /staging/ block instead of the server block. Because ^~ stops Nginx from using your regular PHP location for that folder, nest a copy of the PHP location (location ~ \.php$ { … }) inside it.

Does HTTP Basic Auth stop Google from indexing my staging site?

Yes. Search engine bots get a 401 status and never see the HTML, so there is nothing to index. If pages were indexed before you added the password, they drop out of Google’s results over time once every request returns 401.

How do I reset or change a user’s password?

Run htpasswd again without the -c flag: sudo htpasswd -B /etc/nginx/.htpasswd_staging stagingdev, and enter the new password when asked. Nginx reads the password file on every login check, so you do not need to reload it afterwards.

Will Basic Auth interfere with WP-Cron?

Yes. WP-Cron works by having the server request its own wp-cron.php, and that request has no credentials, so it gets a 401 and scheduled tasks stop. Either exclude wp-cron.php with a location block like the admin-ajax.php one in Step 4, or run cron from the system crontab with WP-CLI (wp cron event run --due-now) or with curl and credentials: curl -u user:pass https://staging.example.com/wp-cron.php.

Next Steps

  1. Share the staging username and password with your team through a password manager, not chat.
  2. If scheduled tasks matter on staging, disable WP-Cron and set up a real cron job so they run despite the password.
  3. Remove the auth_basic lines, or keep them out of your production config, when the site goes live.
all_in_one_marketing_tool