https://linguinecode.com/post/enable-wordpress-rest-api-cors
How to enable CORS on your WordPress REST API
Are you trying to customize the Access-Control-Allow-Headers
property for your WordPress API?
I wrote an article about, “How to fetch WordPress data with JavaScript“. This is usually done because you want to create a headless WordPress site.
Now that you got WordPress rest API up and running, you might not want to let anyone ping your site but your own site only.
First, before you enable CORS on your WordPress site you need to host your WordPress site. If you’re looking to launch a WordPress site for your blog or business, you might want to look into launching your blog with Bluehost for just *$3.95/mo (49.43% off)*. They make it really easy to select an affordable plan, and create or transfer a domain.
Get started with Bluehost.
Disclaimer: The two Bluehost links above are affiliate links which provide a small commission to me at no cost to you. These links track your purchase and credit it to this website. Affiliate links are a primary way that I make money from this blog and Bluehost is the best web hosting option for new bloggers.
Let’s dive into enabling configuring your CORS settings.
Setup your header CORS function
In your functions.php file add the following code.
<?php
function initCors( $value ) {
$origin_url = '*';
// Check if production environment or not
if (ENVIRONMENT === 'production') {
$origin_url = 'https://linguinecode.com';
}
header( 'Access-Control-Allow-Origin: ' . $origin_url );
header( 'Access-Control-Allow-Methods: GET' );
header( 'Access-Control-Allow-Credentials: true' );
return $value;
}
In the example above, I’ve set the variable $origin_url
to equal the asterisk (*
), which means all.
But in the following if conditional
, I’m checking if the environment is in production mode, change the $origin_url
value to my main site URL.
This is helpful when you’re testing locally, or maybe testing an environment that is not production.
This is also assuming that $origin_value
is from a different server or site, that is making the request to your WordPress site.
If you want to only allow same origin, you will have to change the value of Access-Control-Allow-Origin
to
header( 'Access-Control-Allow-Origin: ' . esc_url_raw( site_url() ) );
Enable your init CORS function
The next step is to attach the function that was created above to a WordPress filter called rest_pre_serve_request
.
But before you do that, you must remove the current one.
And we’re going to add this under the WordPress action called rest_api_init
.
<?php
// ... initCors function
add_action( 'rest_api_init', function() {
remove_filter( 'rest_pre_serve_request', 'rest_send_cors_headers' );
add_filter( 'rest_pre_serve_request', initCors);
}, 15 );
Allow multiple origins
You may add multiple origin support. All you need to do is create an array of allowed origins, and check if the origin coming in is allowed.
function initCors( $value ) {
$origin = get_http_origin();
$allowed_origins = [ 'site1.example.com', 'site2.example.com', 'localhost:3000' ];
if ( $origin && in_array( $origin, $allowed_origins ) ) {
header( 'Access-Control-Allow-Origin: ' . esc_url_raw( $origin ) );
header( 'Access-Control-Allow-Methods: GET' );
header( 'Access-Control-Allow-Credentials: true' );
}
return $value;
}
I like to tweet about WordPress and post helpful code snippets. Follow me there if you would like some too!
https://stackoverflow.com/questions/25702061/enable-cors-on-json-api-wordpress#:~:text=In%20your%20server%20hosting%20your,php%20file.&text=To-,header(%20'Access-Control-,Allow-Origin%3A%20*'%20)%3B
I've used a few different WordPress API's – but for those of you using the 'official' WP-API, I had much trouble with this CORS — and what I found was that between the .htaccess approach and a few others I stumbled upon… adding this to your theme functions.php worked best.
function add_cors_http_header(){
header("Access-Control-Allow-Origin: *");
}
add_action('init','add_cors_http_header');
Be sure not to use any combinations of these ( .htaccess, header.php, api.php, functions.php ) as it will be angry at you.
Follow
answered Mar 22, 2015 at 23:24
8,57566 gold badges4040 silver badges6868 bronze badges
This worked for v1, but I just came across this again – and I'm not having any luck with v2 yet.
Works with Wordpress API V2. Best solution I could find.
– Hinrich
1
This is the only solution working for me. Some server doesn't allow you to set CORS in htacces
1
This worked for me! A good way to test and make sure it is working is to check the headers — Advanced Rest Client is a good tool.
– Nabha
1
this has not worked for me in Wordpress V5, I've checked the headers and my header is not in there.
@KyleCalica-St – bummer! I haven't used this in a while – / or haven't upgraded any of the apps using it. I know that wp-json is now in core. Some things may have changed. If you figure it out – be sure to come back and add it here. : )
@sheriffderek stackoverflow.com/questions/25702061/…
@sheriffderek these changes here actually changed my headers. However, didn't fix my specific problem.
this has not worked for me in Wordpress V5, the solution is in this post stackoverflow.com/a/60642286/2400373
19
Ok I finally figured out an easy way…
You just have to add:
<? header("Access-Control-Allow-Origin: *"); ?>
On the file api.php, this file is located in wp-content/plugins/json-api/singletons/api.php
I hope it helps more people with the same problem!
https://patchstack.com/articles/wordpress-security-headers/
Table of Contents
What Are WordPress security headers?
Add HTTP Strict Transport Security (HSTS) to WordPress
Add X-Frame-Options security header to WordPress site
X-XSS-ProtectionAdd X-XSS-Protection security header to WordPress site
NGINX ConfigurationX-Content-Type-Options
Add X-Content-Type-Options security header to WordPress site
Add Content Security Policy security header to WordPress site
Frequently asked questions about WordPress security headers
How can I add WordPress security headers automatically?
Why do I need security headers for WordPress?
Why do I need HSTS for WordPress?
How can Patchstack help you to protect your websites?
WordPress Security Headers (or HTTP security headers) were created to protect applications from frequent and common attacks without the need to add or change the code of your applications.
Website or web application security has multiple aspects that need focus and work and one good way to start is by adding security headers.
What Are WordPress security headers?
Security headers for WordPress help you to provide another layer of security to mitigate attacks and protect from various security vulnerabilities.
In this blog post, we will guide you through different types of security headers and help you to add them to your WordPress site to make your site more secure.
If you use Patchstack you can easily enable the "Add security headers" option on the Patchstack hardening tab. (It only works with sites run by Apache (requires .htaccess).
HTTP Strict Transport Security (HSTS) allows web servers to declare that web browsers (or other complying user agents) should only interact with it using secure HTTPS connections, and never via the insecure HTTP protocol.
Example:
Strict-Transport-Security: {parameter1} ; {parameter2}
*max-age
* parameter will set the time, in seconds, for the browser to remember that this site is only to be accessed using HTTPS.
*includeSubDomains
* is an additional parameter that can be used to apply this rule to all of the site's subdomains as well.
Add HTTP Strict Transport Security (HSTS) to WordPress
You can add an HSTS security header to a WordPress site by adding a few lines of code to Apache .htaccess file or to Nginx.conf file. You can see the snippets for both server types below.
Apache Configuration
<VirtualHost 192.168.1.1:443>
Header always set Strict-Transport-Security “max-age=31536000;
includeSubDomains”
</VirtualHost>
NGINX Configuration
add_header Strict-Transport-Security max-age=31536000;
X-Frame-Options
X-Frame-Options protects visitors against Clickjacking attacks. Using an iframe, the content of your site could be loaded inside another website.
This could be abused maliciously when visitors click on a link they believe to be harmless when actually they're navigating inside your website. This can be highly dangerous when the user has previously logged in to a restricted area on your site.
Example:
X-Frame-Options: {parameter}
deny
parameter will completely deny rendering within the iframe.
sameorigin
parameter will deny rendering if origin mismatches.
***allow-from: DOMAIN\***
parameter allows rendering if it is framed by a frame loaded from the specified domain
Add X-Frame-Options security header to WordPress site
You can add an X-Frame-Options security header to your WordPress site by configuring the .htaccess file (Apache). With NGINX you need to edit Nginx.conf file.
Setting sameorigin is recommended.
Apache Configuration
<IfModule mod_headers.c>
Header always append X-Frame-Options SAMEORIGIN
</IfModule>
NGINX Configuration
add_header X-Frame-Options "SAMEORIGIN" always;
X-XSS-Protection
X-XSS-Protection security header allows you to configure the XSS protection mechanism found in popular web browsers. As an example, this could prevent session cookie stealing with persistent XSS attacks when a logged-in visitor is visiting a page with an XSS payload.
Example:
X-XSS-Protection: {paremeter1}; {parameter2}
***0***
parameter disables the filter.
1
parameter enables the filter.
***1; mode=block\***
enables the filter with the 1
parameter and additionally blocks the website to be rendered with mode=block
.
***1; report=https://your-report-url/\***
enables the filter with the 1
parameter, then sanitizes the request and sends the report to the selected URL with report=
parameter.
Add X-XSS-Protection security header to WordPress site
You can add an X-XSS-Protection security header to your WordPress site by configuring the .htaccess file (Apache). With NGINX you need to edit nginx.conf file.
Apache Configuration
<IfModule mod_headers.c>
Header set X-XSS-Protection "1; mode=block"
</IfModule>
NGINX Configuration
add_header X-Xss-Protection "1; mode=block" always;
X-Content-Type-Options
Setting the X-Content-Type-Options header will prevent the browser from interpreting files as something else than declared by the content type in the HTTP headers. It has a lot of configuration options and potential parameters, but the most common parameter used is nosniff
.
Example:
X-Content-Type-Options: nosniff
Add X-Content-Type-Options security header to WordPress site
You can add the X-Content-Type-Options security header to your WordPress site by configuring the .htaccess file (Apache). With NGINX you need to edit nginx.conf file.
Apache Configuration
<IfModule mod_headers.c>
Header set X-Content-Type-Options nosniff
</IfModule>
NGINX Configuration
add_header X-Content-Type-Options "nosniff" always;
Content-Security-Policy
Content Security Policy header helps you reduce XSS risks on modern browsers by declaring, which dynamic resources are allowed to load.
Similar to X-Content-Type-Options, the Content-Security-Policy header has a lot of configuration options and potential parameters, but at this point, we will mention the ones in the example (which are recommended for beginners).
Example:
Content-Security-Policy default-src 'none'; script-src 'self'; connect-src 'self'; img-src 'self'; style-src 'self';
***default-src***
parameter is the default policy for loading content such as JavaScript, Images, CSS, Fonts, AJAX requests, Frames, HTML5 Media.
***script-src***
parameter Defines valid sources of JavaScript.
***connect-src***
parameter applies to XMLHttpRequest (AJAX), WebSocket or EventSource. If not allowed the browser emulates a 400 HTTP status code.
img-src
parameter defines valid sources of images.
***style-src***
parameter Defines valid sources of stylesheets.
Add Content Security Policy security header to WordPress site
You can add a Content-Security-Policy security header to your WordPress site by configuring the .htaccess file (Apache). With NGINX you need to edit nginx.conf file.
Apache Configuration
Header set Content-Security-Policy default-src 'none'; script-src 'self'; connect-src 'self'; img-src 'self'; style-src 'self';
NGINX Configuration
add_header Content-Security-Policy "default-src 'none'; script-src 'self'; connect-src 'self'; img-src 'self'; style-src 'self';";
Frequently asked questions about WordPress security headers
How can I add WordPress security headers automatically?
If you use Patchstack you can easily enable the "Add security headers" option on the Patchstack hardening tab. (It only works with sites run by Apache (requires .htaccess).
You can add security headers automatically with Patchstack. Get started with Patchstack here.
Why do I need security headers for WordPress?
Security headers for WordPress help you to provide another layer of security to mitigate attacks and protect from various security vulnerabilities.
Why do I need HSTS for WordPress?
HTTP Strict Transport Security (HSTS) allows web servers to declare that web browsers (or other complying user agents) should only interact with it using secure HTTPS connections, and never via the insecure HTTP protocol.
How can Patchstack help you to protect your websites?
- Get automated fixes for vulnerabilities before they are exposed to the world.
- Gain an overview of blocked threats and attacks against your websites.
- Patch the main risk for website security – the plugin vulnerabilities.
- Identify vulnerable plugins and know which ones should be updated.
- No hassle 1-minute setup.
Try Patchstack now, cancel anytime, 30-day money-back guarantee.