how-to-fix-401-403-wordpress-rest-api-errors

Fix 401 and 403 WordPress REST API Errors on LiteSpeed

Fix 401 Unauthorized and 403 Forbidden WordPress REST API errors on LiteSpeed and Cloudflare. Covers .htaccess headers, WAF rules, and Python User-Agent fixes.

Are your automated WordPress scripts failing with 401 Unauthorized or 403 Forbidden errors even though your Application Password is correct?

Nothing stalls a publishing pipeline faster than an API request that works on localhost but gets blocked in production.

The good news is that these errors almost always come down to three predictable culprits: stripped Authorization headers on LiteSpeed or Apache, Cloudflare bot filters, or a missing User-Agent header. In this guide, we will show you how to diagnose and fix both 401 and 403 errors in minutes.

Executive Summary

  • 401 Means Missing or Rejected Auth: Your server is stripping the Authorization header before PHP sees it, or your Application Password contains unstripped spaces.
  • 403 Means Firewall or Role Block: Cloudflare, ModSecurity, or a WordPress security plugin is blocking your script’s User-Agent or IP address.
  • Two-Minute Server Fix: Adding one RewriteRule or SetEnvIf directive to .htaccess passes Basic Auth headers cleanly into WordPress on LiteSpeed and Apache.
  • Safe Client Headers: Sending a custom User-Agent and stripping spaces from Application Passwords resolves most Python client blocks immediately.

Table of Contents

Quick Diagnosis: 401 vs. 403 REST API Errors

Before editing server files, check the exact status code and response body your script receives. That single clue tells you whether WordPress or your firewall rejected the request.

Status CodeResponse Body ClueMost Likely CauseWhere to Fix It
401 Unauthorizedrest_cannot_create or Sorry, you are not allowed...LiteSpeed or Apache stripped the Authorization header.Add HTTP_AUTHORIZATION rule in .htaccess.
401 Unauthorizedincorrect_passwordApplication Password has spaces or wrong username.Strip spaces and re-encode Base64 token.
403 ForbiddenHTML page mentioning CloudflareCloudflare Bot Fight Mode or WAF blocked Python.Add custom User-Agent and WAF skip rule.
403 ForbiddenJSON rest_forbidden or security plugin messageWordfence, iThemes, or user role lacks publish_posts.Check user role and security plugin REST settings.
Fix 401 and 403 WordPress REST API Errors on LiteSpeed Data Chart

Most 401 and 403 errors happen at the web server or CDN layer before WordPress even runs. Follow these three steps to let authenticated REST requests through safely.

Step 1: Preserve the Authorization Header in .htaccess

When PHP runs as CGI, FastCGI, or LSAPI on LiteSpeed and Apache, the web server often strips the Authorization header for security. Open your site’s root .htaccess file and add this rule right above # BEGIN WordPress:

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
</IfModule>

Save the file and test your request again. WordPress will now receive your Basic auth token in $_SERVER['HTTP_AUTHORIZATION'].

Pro Tip: If your host uses Nginx instead of LiteSpeed or Apache, Nginx passes Authorization headers to PHP-FPM by default. Check your fastcgi_params only if HTTP_AUTHORIZATION is explicitly unset.

Step 2: Allow /wp-json/ in Cloudflare WAF

If your response body contains HTML from Cloudflare instead of JSON from WordPress, Cloudflare’s Bot Fight Mode or Managed Rules blocked your script. Open your Cloudflare dashboard and go to Security > WAF > Custom rules.

Create a rule that matches (http.request.uri.path contains "/wp-json/") and (http.user_agent contains "TeckScaler-Automation") (replace with your own unique User-Agent string). Set the action to Skip for Super Bot Fight Mode or Rate Limiting, or restrict it further to your deployment server’s IP address for maximum safety.

Step 3: Verify Pretty Permalinks and User Role

In your WordPress admin dashboard, go to Settings > Permalinks and confirm that Plain is not selected. WordPress REST routes require pretty permalinks such as Post name.

Next, check Users > All Users and verify that the account owning the Application Password has the Editor or Administrator role. Subscribers and Contributors cannot publish posts or upload media via /wp-json/wp/v2/.

Method 2: Fix Headers and Auth Encoding in Python

Even when your server is configured properly, small mistakes in your Python client can trigger 401 or 403 responses.

Step 1: Replace the Default Python User-Agent

By default, Python’s requests library sends User-Agent: python-requests/2.x.x. Many hosting firewalls and CDNs block that string automatically as scraper traffic.

Always override User-Agent with a clear, descriptive identifier for your automation tool:

headers = {
    "Authorization": f"Basic {encoded_token}",
    "User-Agent": "TeckScaler-Automation/1.0",
    "Accept": "application/json",
}

Step 2: Strip Spaces from Application Passwords

WordPress displays Application Passwords in groups of four characters separated by spaces, such as abcd efgh ijkl mnop qrst uvwx. If you encode those spaces into your Base64 token or forget to remove them in .env, authentication fails with 401.

Clean the password string in Python before encoding it:

import base64

clean_password = app_password.replace(" ", "").strip()
raw_credentials = f"{username}:{clean_password}".encode("utf-8")
encoded_token = base64.b64encode(raw_credentials).decode("utf-8")

Step 3: Inspect the Response Headers with a Debug Script

Run a quick diagnostic check against /wp-json/wp/v2/users/me. That endpoint confirms whether WordPress recognizes your user account and permissions.

import requests

resp = requests.get(
    "https://example.com/wp-json/wp/v2/users/me",
    headers=headers,
    timeout=15,
)
print("Status:", resp.status_code)
print("Server:", resp.headers.get("Server"))
print("Body:", resp.text[:300])

If /users/me returns 200 OK with your user JSON, your authentication works completely.

Note: Always use https:// in WP_SITE_URL. WordPress disables Application Passwords over plain http:// on live environments unless WP_ENVIRONMENT_TYPE is set to local.

Additional Security Plugin Checks

If both .htaccess and Cloudflare look clean, check your WordPress security plugins:

  • Wordfence: Look under Wordfence > Firewall > All Firewall Options for rules blocking REST API authentication or XML-RPC/REST endpoints.
  • Disable REST API Plugins: Plugins like “Disable WP REST API” or theme snippets in functions.php using rest_authentication_errors can reject unauthenticated or non-cookie requests. Whitelist is_user_logged_in() or specific routes if needed.
  • LiteSpeed Cache: Make sure LiteSpeed Cache is not caching /wp-json/ error responses. Add /wp-json/ to LiteSpeed Cache > Cache > Excludes > Do Not Cache URIs.

Frequently Asked Questions

Why does GET /wp-json/wp/v2/posts work while POST returns 401?

Reading published posts is public by default, so WordPress does not check your Authorization header on GET requests. When you send a POST, WordPress looks for valid credentials, which fails if your server stripped the header.

Does LiteSpeed Enterprise use the same .htaccess rule as Apache?

Yes. LiteSpeed Web Server is drop-in compatible with Apache .htaccess rewrite rules, including RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}].

Can Cloudflare cache a 403 error on the REST API?

Usually Cloudflare does not cache 403 responses by default, unless a custom Page Rule or Cache Rule forces caching on error codes. Always bypass cache for /wp-json/* in Cloudflare.

Is it safe to disable Basic Auth blocking in ModSecurity?

Yes, as long as your WordPress site runs strictly over HTTPS and you use Application Passwords instead of your primary admin password. You can revoke any Application Password in one click from your WordPress profile.

You May Also Like

We hope this guide helped you fix 401 and 403 WordPress REST API errors on LiteSpeed and Cloudflare. Written by the TeckScaler Editorial Engineering Team. Continue building your automation stack with our related guides:

Primary Sources and References

Leave a Reply

Your email address will not be published. Required fields are marked *