WP REST API and Access-Control-Allow-Origin

In one of my project I use a Wordpress REST Api. When I was enabled cache by WP Super Cache plugin I have an error now:

XMLHttpRequest cannot load http://api.mydomain.com/wp-json/wp/v1/posts. Origin http://mydomaintwo.com is not allowed by Access-Control-Allow-Origin.

How can I fix it?

Topic wp-api plugin-wp-supercache rest-api api cache Wordpress

Category Web


I found a .htaccess solution, but I will be happy if anyone know a working PHP solution.

It's my .htaccess with multiple domain access support and access for only GET request:

# CORS Headers
<ifModule mod_headers.c>
    SetEnvIf Origin "^http(s)?://(.+\.)?(localhost:8080|example\.com|example\.net)$" origin_is=$0 
    Header always set Access-Control-Allow-Origin %{origin_is}e env=origin_is
    Header always set Access-Control-Allow-Methods "GET"
    Header always set Access-Control-Allow-Headers "X-Requested-With, content-type"
</ifModule>


# BEGIN WordPress
... # default WP rules
# END WordPress


# CORS OPTIONS
RewriteCond %{REQUEST_METHOD} OPTIONS
RewriteRule ^(.*)$ $1 [R=200,L]

If you want to use only one domain, you can remove the line starts with "SetEnvIf...", and in the next put:

Header always set Access-Control-Allow-Origin: "http://example.com"

If you want to use also other request, you can separated it by a comma:

Header always set Access-Control-Allow-Methods "GET, POST, PUT, DELETE"

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.