AIForum.

How to Configure CORS for Local AI Servers Accessed from WordPress

On this page

THE SHORT ANSWER

CORS errors between WordPress and a local model server are usually fixed on the model server, not in WordPress. This guide explains which request path triggers CORS, how to allow your WordPress origin on Ollama, and why proxying through a WordPress REST route avoids the problem entirely.
Quick facts

If a browser-side script in WordPress cannot reach your local model server, the fix is almost always made on the model server, not in WordPress. CORS is enforced by the browser, and the headers that satisfy it must come from the server that answers the request — typically a local runtime such as Ollama listening on port 11434. Adding Access-Control-Allow-Origin to WordPress only changes WordPress’s own responses; it does nothing for a request the browser sends directly to the model.

There are two reliable ways out. The first is to stop making the browser talk to the model at all: route the call through a WordPress REST endpoint and let PHP make the upstream request, which is not subject to CORS. The second is to keep the direct browser call and explicitly allow the WordPress origin on the AI server. This guide covers both, along with the console messages that tell you which one you actually need.

CORS applies to only one of the two request paths

The same-origin policy is a browser rule. It says that a page loaded from one origin cannot read the response of a request to a different origin unless that other server opts in with CORS response headers. Servers, command-line tools, and PHP are not bound by it. That single fact resolves most confusion in WordPress + local AI setups, because there are two very different paths a request can take.

Request pathWho makes the final requestDoes CORS apply?
Browser JavaScript → local AI serverThe browserYes
Browser JavaScript → WordPress REST route → PHP → local AI serverPHP on your serverNo

The two paths also fail differently. A direct browser call produces a console message naming the origin, the request URL, and a missing Access-Control-Allow-Origin header. A proxied call produces a WordPress-side error such as a connection timeout or a WP_Error, because the browser never sees the model server at all.

Path 1: Proxy the model through a WordPress REST route

This is the more robust option, and it is the one to choose when your WordPress admin runs over HTTPS while the model server is plain HTTP on localhost. It removes CORS from the equation entirely and keeps the model endpoint off the public network.

Prerequisites

  • WordPress must be able to reach the model server over the network. If WordPress and the model share a VPS, 127.0.0.1 is enough; on shared hosting a direct connection to a local port is not possible and you need a tunnel or a proxy host instead.
  • A model must be pulled and the runtime running. For Ollama, ollama pull llama3.2 downloads a model and curl http://localhost:11434/api/tags confirms the API answers.
  • Application Passwords should be available if you intend to authenticate from outside the browser session. The commonly used filter is add_filter( 'wp_is_application_passwords_available', '__return_true' );.

Register the proxy endpoint

Add a route that requires a capability check, so the model is not exposed to anonymous visitors. The pattern below follows the custom-endpoint approach used for AI integrations in WordPress:

add_action( 'rest_api_init', function () {
    register_rest_route( 'ai/v1', '/generate', array(
        'methods'             => 'POST',
        'callback'            => 'aiforum_proxy_generate',
        'permission_callback' => function () {
            return current_user_can( 'edit_posts' );
        },
    ) );
} );

Call the local model from PHP

function aiforum_proxy_generate( WP_REST_Request $request ) {
    $body = array(
        'model'  => 'llama3.2',
        'prompt' => sanitize_text_field( $request->get_param( 'prompt' ) ),
        'stream' => false,
    );

    $response = wp_remote_post( 'http://127.0.0.1:11434/api/generate', array(
        'timeout' => 120,
        'headers' => array( 'Content-Type' => 'application/json' ),
        'body'    => wp_json_encode( $body ),
    ) );

    if ( is_wp_error( $response ) ) {
        return new WP_Error( 'ai_upstream_unreachable', $response->get_error_message(), array( 'status' => 502 ) );
    }

    return json_decode( wp_remote_retrieve_body( $response ), true );
}

Note the timeout value. Local generation can take far longer than a typical HTTP request, and the WordPress default will cut the connection before the model finishes.

Call the route from browser JavaScript

The browser now talks only to your own domain, so no CORS headers are involved. Include the REST nonce so the capability check passes:

const res = await fetch( '/wp-json/ai/v1/generate', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'X-WP-Nonce': wpApiSettings.nonce,
  },
  credentials: 'same-origin',
  body: JSON.stringify( { prompt: 'Write a meta description for this post.' } ),
} );

Expected result: the request appears in the browser network panel as a same-origin call to /wp-json/ai/v1/generate, with no Access-Control-* headers involved. If the model is unreachable, you get a JSON error with status 502 rather than a CORS message.

Path 2: Allow the WordPress origin on the local AI server

If you genuinely need the browser to call the model directly — for example, a streaming interface that bypasses PHP — the model server must be told which origins it will answer. Ollama reads an environment variable, OLLAMA_ORIGINS, at startup. By default it accepts requests from localhost-style origins; your WordPress site’s real origin is not one of them, which is exactly why the browser blocks the response.

OLLAMA_ORIGINS="https://example.com,https://www.example.com" ollama serve

On a systemd-managed install, override the unit rather than editing the packaged file:

sudo systemctl edit ollama.service
[Service]
Environment="OLLAMA_ORIGINS=https://example.com"

Then reload and restart. The variable is read when the service starts, so a running process will not pick up the change.

Verification: send a preflight request with curl and read the response headers. Because curl is not a browser, it will show you the headers even in cases where the browser would still refuse the request.

curl -i -X OPTIONS http://127.0.0.1:11434/api/generate 
  -H "Origin: https://example.com" 
  -H "Access-Control-Request-Method: POST" 
  -H "Access-Control-Request-Headers: content-type"

Look for Access-Control-Allow-Origin in the response. If it is absent, the origin did not match and the browser will block the real request.

Why the preflight request exists

A POST carrying Content-Type: application/json is not a “simple” request, so the browser first sends an OPTIONS request describing what it intends to do. The server must reply with Access-Control-Allow-Methods and Access-Control-Allow-Headers that cover it. Custom headers such as X-WP-Nonce or Authorization also trigger this step. If you see a preflight failure in the console but the plain curl request works, the OPTIONS handling is the place to look.

What the WordPress-side CORS snippet actually does

Many tutorials suggest adding this to functions.php:

function add_cors_http_header(){
    header("Access-Control-Allow-Origin: *");
    header("Access-Control-Allow-Methods: GET, POST, OPTIONS, DELETE");
    header("Access-Control-Allow-Headers: Authorization, Content-Type");
}
add_action('init','add_cors_http_header');

Two caveats are worth knowing before you paste it in. First, these headers describe WordPress’s responses. They cannot authorize a response coming from a different server, so they will not fix a direct browser-to-model call. Second, WordPress core’s REST controller already emits CORS headers that reflect the requesting origin and sets Access-Control-Allow-Credentials: true. A blanket wildcard header added on init is therefore redundant for REST routes and can conflict with credentialed requests, because browsers reject Access-Control-Allow-Origin: * when credentials are included. If you need to adjust WordPress’s own CORS behavior, hook into the REST layer rather than sending headers on every request, and verify the result with a real browser rather than curl.

Troubleshooting: read the console message before changing anything

Work from the cheapest check to the most invasive, and stop as soon as a step explains the symptom.

  1. Confirm where the request originates. Open the browser network panel. If the failing request goes to 11434 or another model port, CORS applies and you need Path 2 or a switch to Path 1. If it goes to /wp-json/..., CORS is not your problem.
  2. Copy the exact error text. “No ‘Access-Control-Allow-Origin’ header is present” points at the model server’s origin configuration. “Response to preflight request doesn’t pass access control check” points at OPTIONS handling. “Blocked by CORS policy” with a redirect named in the message points at a proxy rewriting the request.
  3. Check for a browser-level block rather than CORS. Browsers have been tightening requests from public HTTPS pages to local and private network addresses, and some configurations block or prompt before any CORS header is evaluated. If the console wording mentions mixed content, insecure content, or local network access rather than CORS, changing OLLAMA_ORIGINS will not help.
  4. Test the origin header with curl. Run the preflight command above with your real origin. No Access-Control-Allow-Origin in the output means the server is not configured for that origin.
  5. Restart the model service after editing environment variables. A stale process keeps the old allow-list.
  6. Check anything sitting in front of the model. A reverse proxy, tunnel, or CDN can strip or rewrite CORS headers. Verify the headers at the point the browser reaches, not only on localhost.
  7. Confirm the origin string matches exactly. Scheme, host, and port all count. https://example.com and https://www.example.com are different origins, and a non-standard port must be included.

If none of these steps explains the failure, the missing diagnostic information is usually the exact console message plus the response headers at the URL the browser actually requested. Capture both before changing code.

Security and operational tradeoffs

Opening CORS on a model server is a permission grant, and it deserves the same care as any other one.

  • Never combine a wildcard origin with credentials. Browsers reject it, and if they did not, it would let any site on the internet drive your model using a logged-in user’s session.
  • Keep the model bound to localhost where possible. A local runtime that accepts requests from any application with network access is convenient on a private VPS and dangerous on a public interface.
  • Prefer Path 1 for authenticated work. A WordPress REST route can enforce current_user_can(), rate-limit, and log usage. A directly exposed model port typically enforces none of that.
  • Expect long request times. Local generation on modest hardware is slow compared with a hosted API, so set generous timeouts and consider whether streaming is required before choosing the direct-browser path.
  • Remember that CORS is not access control. It is a browser-enforced reading restriction. Any non-browser client can still call an open model endpoint.

A practical decision rule

If your WordPress admin is served over HTTPS, or if the model call should only be available to logged-in editors, proxy through a WordPress REST route and skip CORS configuration entirely. If you need low-latency streaming straight from the browser and the model server is on a trusted network, configure OLLAMA_ORIGINS with your exact origin, verify the preflight response with curl, and restart the service. Whichever you choose, confirm the fix in a real browser: curl shows headers, but only the browser tells you whether the request is actually allowed.

If you hit a case this guide does not cover, share your WordPress version, model runtime, the exact console message, and the response headers you observed in the community discussion — those four details are usually enough for someone else to identify the cause.

FAQ

Does CORS apply to wp_remote_post calls from WordPress to a local model?

No. CORS is enforced by browsers. A request made by PHP on your server is not subject to the same-origin policy, so no CORS headers are needed for that path.

Why does curl reach the model but the browser still fails?

curl does not enforce CORS and will display response headers regardless. The browser additionally requires that the server return an Access-Control-Allow-Origin value matching the page's origin, and that preflight requests for non-simple calls succeed.

Can I use Access-Control-Allow-Origin: * together with cookies or nonces?

No. Browsers reject a wildcard origin when the request includes credentials. The server must echo the specific origin instead.

Do I need to restart Ollama after changing OLLAMA_ORIGINS?

Yes. The variable is read when the service starts, so an already-running process keeps its previous allow-list until it is restarted.

Is adding CORS headers in functions.php enough to fix a direct browser call to the model?

No. Headers added in WordPress describe WordPress's own responses. The model server must send its own CORS headers, which is why OLLAMA_ORIGINS or a proxy is required.

References

  1. https://davidshusterman.hashnode.dev/the-developers-guide-to-wordpress-rest-api-ai-integration
  2. https://d0a1.es/en/connect-ollama-wordpress-guide-2026/

Related terms

Same-origin policy
A browser rule that prevents a page from reading responses from a different scheme, host, or port unless that server opts in.
Preflight request
An automatic OPTIONS request the browser sends before a non-simple request, such as a JSON POST or one with custom headers, to ask the server what it permits.
Access-Control-Allow-Origin
The response header that names which origin may read the response. It must be sent by the server that answers the request.
OLLAMA_ORIGINS
An environment variable that sets which browser origins an Ollama server will answer. It is read when the service starts, so changes require a restart.
Server-side proxy
A pattern where the browser calls a same-origin WordPress REST route and PHP makes the upstream request to the model, removing the browser from the cross-origin path.

Leave a Reply

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