October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run ScanOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk10 min

How to Update CORS Rules in .htaccess on WordPress and Apache

A practical guide to updating Apache CORS rules for WordPress: prerequisites, safe origin policies, preflight headers, credentials, testing, and fixes.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

To fix a missing Access-Control-Allow-Origin header, add a narrowly scoped Apache Header rule in the .htaccess file that serves the requested WordPress API or asset—but only after confirming that Apache allows FileInfo overrides and has mod_headers loaded. Use the exact frontend origin for private or credentialed requests; reserve * for genuinely public, anonymous access.

What CORS controls—and what .htaccess can change

Cross-Origin Resource Sharing (CORS) is enforced by the browser. A page loaded from one origin (scheme, host, and port) may request another origin, but browser JavaScript can read the response only when the server returns compatible CORS headers. Apache can add those response headers with the Header directive supplied by mod_headers.

As an Amazon Associate I earn from qualifying purchases.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

CORS is not authentication, authorization, or a substitute for WordPress permissions and nonces. It only controls whether a browser script is allowed to read a response. A server must still protect private REST routes, validate users, and enforce application-level access rules.

An .htaccess edit affects the directory containing that file and its descendants. A rule in the document-root file can therefore affect every response, while a file in a narrower API or asset directory limits the change. The host must permit per-directory overrides; otherwise Apache ignores the file or rejects the directive.

#1 Best Overall
Sale
TOZO A1 Wireless Earbuds Bluetooth 5.3 Light Weight in Ear Headphones | IPX5 Waterproof,2 Mics for AI Calls,Immersive Premium Sound Bass Headset with Charging Case,32 EQ via App Black
  • [Ultra-Lightweight Ear Buds Designed for Small Ears] Each earbud weighs only 3.7g and features a compact, ergonomic in-ear design made especially for small ears. Secure, low-profile, and comfortable for workouts, all-day wear or overnight sleeping.The ultra-slim profile sits flush in your ear with no hard edges poking or rubbing, so you can even sleep on your side without discomfort.
  • [Immersive Stereo Sound with TOZO OrigX Technology] TOZO OrigX tuning delivers clear vocals, balanced mids, and natural stereo sound for music, podcasts, and videos.
  • [Long Battery Life for Daily Use] Get up to 7 hours of playtime on a single charge, with up to 32 hours total using the charging case—ideal for workdays, commuting, and extended listening sessions.
  • [Bluetooth 5.3 & Stable Connection] Bluetooth 5.3 provides fast pairing, stable wireless performance, and reduced dropouts as you move around home or office.
  • [Deep Bass with Clear Vocals] High-performance drivers produce punchy bass while keeping vocals clean and detailed for everyday listening.

Prerequisites before editing

Apache must allow the directive

The server administrator controls .htaccess processing with AllowOverride and, on newer Apache installations, AllowOverrideList. Header belongs to Apache’s FileInfo override class. If the virtual host uses AllowOverride None, or does not allow this directive, a WordPress administrator cannot make the change from .htaccess. Ask the host to place the rule in the virtual-host configuration or enable the required override class.

mod_headers must be loaded

The Header directive is provided by mod_headers and can run in server, virtual-host, directory, or .htaccess context. The examples below wrap the rule in <IfModule mod_headers.c> so a missing module does not itself cause a syntax failure, but the header will not be emitted until the module is available.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Back up the current file

  1. Download or copy the existing document-root .htaccess before making any change.
  2. Record the original permissions and the exact location of the backup.
  3. Add one small, reversible block rather than replacing WordPress’s rewrite rules.

A syntax mistake in .htaccess can produce a 500 response for the whole site, so keep a hosting-panel file manager, SFTP access, or another recovery path available.

Choose the correct CORS policy

Situation Access-Control-Allow-Origin Credentials Scope and cautions
Public, anonymous assets or API data * No cookies or other credentials Use only for resources that really may be read by any website.
One private frontend Exact origin such as https://app.example.com Can be enabled explicitly Include scheme, host, and port; never include a path or trailing slash.
Several trusted frontends One selected value from a fixed allowlist Can be enabled explicitly Validate the incoming Origin; do not reflect every value sent by a client.
Responses vary by requesting origin Selected origin Depends on the application Send Vary: Origin so caches do not reuse one origin’s response for another.

The safest policy is the minimum set of origins and resources required for the site to work. A wildcard on every response can expose content that never needed cross-origin access.

Apply a public, non-credentialed rule

Use this only when any website may read the resource and the request does not use cookies or other credentials:

Rank #2
Sale
Smart Watch for Men Women Compatible with iPhone Samsung Android Phone 1.69 inch Full Touch Screen IP68 Waterproof Bluetooh Fitness Tracker Heart Rate/Sleep Monitor (Black)
  • 【IP68 Waterproof Multifunctinal Smart Watch】Torjalph fitness activity tracker smart watch is IP68 waterproof technology ,you can wear it when swimming,handwashing,it's rain-proof which means that you perform multiple exercise modes outside without worrying about sweat or rain corroding your fitness smart watch,and this watch equipped with a 230 mAh large capacity battery magnetic charging ,and this sports activity tracker watch can be used 5-7 days If fully charged.
  • 【Larger 1.83'' Full Screen Watch & Multi-dial Selection】1.83 inch full HD color touch screen smart watch for men / women provides excellent 240*284 resolution image quality ,This Bluetooth smart watch offers a better touch experience and remarkable immersion and ,more than 200 watch faces for you to choose from App"Da Fit ", you can change the dial style according to your mood to wear keeping the world on your wrist
  • 【Accurate Activity Tracker Smart Watch 】sports watch activity tracker uses sweat and dust resistant breathable silicone strap, our Fitness Tracker Smart Watch for Android iOS Phones supports 12 sports modes,walking,running,bicycle,swimming,badminton,basketball,football,rope skipping. This bluetooth calls smart watch for men women is lightweight and stylish, bringing more convenient and relaxing sports experience while also providing more protection.
  • 【Your 24 Hour Personal Daily Health Monitor】Fitness watch for women men full touch screen IP67 waterproof bluetooth smartwatch for Android iOS Phones with heart rate blood pressure monitor multifunction Andriod smart watch with steps counter sleep monitor sports fitness watch, monitoring blood oxygen saturation allows you to understand your physical condition in real time to track fitness progress ,to know your health status in time.
  • 【More Functions Bluetooth Call Smart Watch】This fitness activity smart watch full screen for iPhone and Android phones includes a bunch of new features including:The bluetooth smart watch can hang up the phone, receive and display WhatsAPP /Text /Facebook /Twitter /Messenger reminder.Support sedentary reminder, alarm clock, stopwatch, timer,weather information,music control, remote camera control compatible with Android 5.0 and above or iOS 9.0 and above smartphones.
<IfModule mod_headers.c>
    Header always set Access-Control-Allow-Origin "*"
</IfModule>

always makes Apache add the header across response conditions where the header table is available, including many error responses. It does not make an otherwise protected endpoint public; it only tells browsers that cross-origin reading is allowed. Scope the block to the directory or resource type that is intentionally public instead of placing it globally without a reason.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Allow one known frontend origin

For a private application, replace the example with the frontend’s exact origin:

<IfModule mod_headers.c>
    Header always set Access-Control-Allow-Origin "https://app.example.com"
    Header always set Vary "Origin"
</IfModule>

The origin is case-sensitive in practice for matching purposes and consists only of scheme, host, and port. These are different origins: http://app.example.com, https://app.example.com, https://app.example.com:8443, and https://www.example.com. Do not write https://app.example.com/, append a route such as /dashboard, or list a full URL with a path.

Vary: Origin is important whenever the response can differ according to the request’s Origin. It tells an intermediary cache that the origin is part of the response’s selection criteria.

Handle preflight OPTIONS requests

Browsers send a preflight OPTIONS request before many cross-origin requests, especially when the actual method or headers are not considered simple. The server must answer with the methods and request headers the application really uses.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
New Bee Guitar Cable 10ft Electric Instrument Bass AMP Cord
  • [Low Noise High Fidelity] New bee guitar cord with 22AWG oxygen-free-copper center conductors provides enhanced signal transfer, the PVC insulation material and the high-density stranded copper double shield provide noise rejection for quiet operation
  • [Ideal for Choice] New bee 1/4 straight and right angle metal connectors, ensures a secure connection in any instrument, pedal, or amp jack. L shape great fro on stage guitar stands
  • [Wide Compatible] Suitable for mixer, power amplifier, microphone, effector, decoder, equalizer, electoronic organ, electric guitar, electric bass and other electronic equipments. Widely used in the installation of smart home, karaoke speaker, professional stage audio, etc
  • [Easy Disassemble] Making incidental repairs quick and easy! Very nice, flexible cable
  • [Dont Hesite to Order] 24 hours customer services and professional technology team are standing by
<IfModule mod_headers.c>
    Header always set Access-Control-Allow-Origin "https://app.example.com"
    Header always set Access-Control-Allow-Methods "GET, POST, OPTIONS"
    Header always set Access-Control-Allow-Headers "Content-Type, Authorization"
    Header always set Vary "Origin"
</IfModule>

Do not copy the method or header lists unchanged if your application needs less—or more. The browser compares the requested method and header names with these response values. Header names are matched case-insensitively, but spelling a required name incorrectly still causes the preflight to fail. Add only methods such as PUT, PATCH, or DELETE when the endpoint actually supports them.

Apache may still pass OPTIONS to WordPress or another handler. The CORS headers do not by themselves guarantee a successful status code; inspect the complete preflight response and make sure the application, rewrite rules, authentication layer, and any proxy permit the request.

Configure credentialed requests safely

Cookies, HTTP authentication, and other credentialed browser requests require an explicit origin. They cannot use *. Add the credentials header only when the application genuinely needs it:

<IfModule mod_headers.c>
    Header always set Access-Control-Allow-Origin "https://app.example.com"
    Header always set Access-Control-Allow-Credentials "true"
    Header always set Access-Control-Allow-Methods "GET, POST, OPTIONS"
    Header always set Access-Control-Allow-Headers "Content-Type, Authorization"
    Header always set Vary "Origin"
</IfModule>

The frontend must also request credentials using its framework’s or the Fetch API’s credentials setting. A browser will reject a response that combines Access-Control-Allow-Credentials: true with Access-Control-Allow-Origin: *. A bearer token in an Authorization header also triggers preflight in common cases, so list that request header when it is used; continue to enforce the token’s permissions on the server.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Support several trusted origins without reflecting attackers

Apache should emit one approved origin, not a comma-separated list. If several frontends are trusted, the configuration or application must compare the incoming Origin against a fixed allowlist and return the matching value only when it is present in that list. An arbitrary value copied from the request is effectively “allow any origin” and is unsafe for private responses.

Rank #4
BSIMB 15.6" Digital Family Calendar & Chore Chart, No Subscription Fees
  • Digital Family Calendar: BSIMB digital calendar wall touch screen puts an end to your chaotic life. Designed for busy families, the digital calendar keeps you organised and in step with your family. Assign different colours and tasks to each family member to make family scheduling easier and more intuitive.
  • Easy Setup and Auto-Sync: Plug in, connect to WLAN and auto-syn your electric calendar in minutes. Digital wall calendar compatible with Google calendar, iCloud calendar, Outlook calendar, Cozi calendar and Yahoo calendar. Add events directly on the device or through the ecalendar app. Electronic calendar stays current whether you're at work or traveling—no manual updates needed.
  • All-In-One Home Assistant: Smart calendar builds habits and encourage independence with personalised chores. Display daily meal plan to reduce the daily ‘What's for dinner?’ stress. To-do lists keep track of everything you want. Turning chores into valuable achievements with stars and rewards, making life easier and more enjoyable.
  • Manage Anytime Anywhere: BSIMB electronic calendar for family stay connected with the powerful ecalendar app. Access and manage your digital wall calendar anytime, anywhere with free features like stars & rewards, photo screensaver, chore charts, meals plans, to-do lists etc. Electronic planner paid features like Magic Import tailor advanced tools for users with special needs.
  • Stay in Touch with Loved Ones: Share photos or videos from your phone to electronic wall calendar with app, instantly update your life moment, and keep in touch with your family, especially those who are far away; you can also surprise your smart calendar digital wall by sending him a wish card; it's also great for keeping tech-illiterate elders in touch with the youngsters.

Dynamic allowlists are usually clearer in WordPress code, the API application, or a reverse proxy than in a long .htaccess expression. Whichever layer performs the selection, return Vary: Origin and ensure that disallowed origins receive no allow-origin header (or an intentional error) rather than a reflected value.

Never use Access-Control-Allow-Origin: null as a shortcut. Sandboxed documents and other hostile contexts can send a null origin, so it is not a safe replacement for a real allowlist.

Scope the rule to WordPress resources

Use a narrower directory when possible

If the API or static files are served from a directory you control, put the rule in that directory’s .htaccess. Apache applies it there and below, leaving unrelated pages untouched. This is the simplest way to avoid adding CORS headers to login pages, administration screens, HTML documents, and private downloads.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Be cautious in the document root

WordPress commonly serves REST requests under /wp-json/ from the document root, so a root-level rule can affect the entire site. If a root file is unavoidable, use an Apache 2.4 expression or another host-supported condition to match only the intended URI, and test that the condition is accepted in .htaccess on your host. Do not paste a conditional syntax your host’s Apache version does not support.

Limit static assets by type only when appropriate

An asset rule can target the extensions actually consumed by another site, such as JSON, fonts, or images. Fonts often need CORS for cross-origin embedding, while HTML pages usually do not. Confirm the resource list before adding a broad extension match.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Account for WordPress and plugin-generated headers

WordPress includes send_origin_headers(), which handles OPTIONS requests and can send access-control headers for an allowed origin or return a 403 response when the origin is not allowed. A custom endpoint, security plugin, cache plugin, CDN, or reverse proxy may also add headers.

Inspect the final response before adding an Apache rule. Two layers that emit different Access-Control-Allow-Origin values create a conflicting response; browsers expect one coherent value. Remove or disable the duplicate at the layer that should own the policy, rather than trying to mask it with another Header set directive. If WordPress is intentionally enforcing an allowlist, keep that policy in one place and make Apache agree with it or leave the header to WordPress.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Test the actual response

Test a preflight from the command line

Replace the URL, origin, method, and requested headers with the values used by the browser:

curl -i -X OPTIONS "https://example.com/wp-json/wp/v2/posts" 
  -H "Origin: https://app.example.com" 
  -H "Access-Control-Request-Method: POST" 
  -H "Access-Control-Request-Headers: Content-Type, Authorization"

Check the status and response headers. You should see one matching Access-Control-Allow-Origin, an allowed method containing POST, an allowed-headers value containing both requested names, and Access-Control-Allow-Credentials: true if the request is credentialed. A 403, redirect, authentication challenge, or server error is still a failed preflight even if one CORS header is present.

Test the final request

curl -i "https://example.com/wp-json/wp/v2/posts" 
  -H "Origin: https://app.example.com"

Follow redirects while testing. The browser evaluates the response it ultimately receives, and a redirect target can omit the headers present on the first response. Repeat the test with an unapproved origin to verify that the policy does not accidentally reflect it.

Use browser developer tools

  1. Open the browser’s Network panel and reproduce the failing request.
  2. Inspect the OPTIONS request, if one appears, including its status and request headers.
  3. Inspect the actual response after the preflight succeeds.
  4. Look for duplicate allow-origin values, redirects, cached responses, and console messages naming the exact missing or invalid header.

Troubleshoot common failures

Symptom Likely cause Fix
500 Internal Server Error immediately after editing Header is disallowed by AllowOverride/AllowOverrideList, the syntax is unsupported, or mod_headers is unavailable. Restore the backup, ask the host to enable the FileInfo override or place the rule in server configuration, and confirm the module and Apache version.
No header appears The file is ignored, is in the wrong directory, the request is served elsewhere, or a CDN/proxy replaces the response. Confirm the file’s directory scope, verify override support, bypass the cache where possible, and inspect the origin server response.
Duplicate or conflicting allow-origin headers WordPress, a plugin, CDN, and Apache are applying separate policies. Identify every layer in the final response and keep one authoritative rule.
Preflight fails The OPTIONS response lacks the requested method or header, returns an error, redirects, or is blocked by authentication. Compare Access-Control-Request-Method and Access-Control-Request-Headers with the corresponding response headers and make the endpoint answer OPTIONS.
Credential error in the browser The response uses *, omits Access-Control-Allow-Credentials: true, or names the wrong origin. Use the exact origin, enable credentials explicitly, and configure the frontend to send them.
Works for one origin but not another, or changes unpredictably A cache reused a response generated for a different origin. Send Vary: Origin whenever the selected response changes by origin and purge stale cached responses.
The API is on another server The remote server does not send the required header. Change CORS on the API server or proxy. A local WordPress .htaccess file cannot modify a response it does not serve.

Security checklist before going live

  • List the exact API routes or asset types that need cross-origin access.
  • Use a fixed origin for private data and credentials; use * only for public, anonymous resources.
  • Never reflect an arbitrary Origin value and never use null as a workaround.
  • Allow only the methods and request headers the application uses.
  • Keep WordPress authentication, authorization, nonces, and API permission checks enabled.
  • Check the response after redirects and through the production CDN or proxy, not only at the origin server.
  • Verify that exactly one layer owns each CORS header.
  • Include Vary: Origin for origin-dependent responses.

When .htaccess is the wrong layer

Use Apache virtual-host configuration, the application, or a reverse proxy instead when the host disables FileInfo overrides, when several origins require complex allowlist logic, or when the API is not served by the WordPress Apache instance. Centralizing the policy at the layer that knows the endpoint’s authentication and origin rules often prevents plugin and cache conflicts. If the hosting provider will not enable mod_headers or the required override class, no WordPress edit can compensate for that server limitation.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

A practical decision path

  1. Is the resource public and anonymous? If yes, a scoped wildcard may be suitable. If no, continue.
  2. Does the browser send cookies or other credentials? If yes, select an exact origin and add the credentials header; never use *.
  3. Does the request trigger preflight? If yes, answer OPTIONS with the exact methods and request headers required.
  4. Can WordPress or a plugin already emit CORS headers? Inspect the final response and keep one authoritative policy.
  5. Can Apache legally process the rule? Confirm AllowOverride, AllowOverrideList, and mod_headers before troubleshooting the browser.
  6. Does a cache vary the response by origin? Add Vary: Origin and test through the same proxy path used by visitors.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

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

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
Windows Errors? Fix Them Before They SpreadFree repair scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.