Customising cache Response Headers
-
Hi,
I’m trying to set a Access-Control-Allow-Origin header to limit requests from our endpoints to our own domains. We have multiple domains so we need to dynamically check if HTTP_ORIGIN is within our allowed domains.
I have a code which works perfectly for the endpoints and checks the Origin but it only works for the initial request after cache is cleared and on the cached requests I guess the header allows all Origins.
Here is my code for changing the header for our custom endpoint:
add_action('rest_api_init', function() { remove_filter('rest_pre_serve_request', 'rest_send_cors_headers'); add_filter('rest_pre_serve_request', function($value) { $origin = get_http_origin(); $allowed_origins = [ 'https://our.domain.com', 'https://ourdomain.com', 'https://app.ourdomain.com' ]; // Fallback $allowed_origin = 'https://ourdomain.com'; if(in_array($origin, $allowed_origins)) { $allowed_origin = $origin; } header( 'Access-Control-Allow-Origin: ' . esc_url_raw($allowed_origin)); header( 'Access-Control-Allow-Methods: GET, OPTIONS'); if(isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'OPTIONS') { header( 'Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept'); header( 'Access-Control-Max-Age: 86400'); header( 'Cache-Control: public, max-age=86400'); header( 'Vary: origin'); exit(0); } return $value; }); });
Viewing 8 replies - 1 through 8 (of 8 total)
Viewing 8 replies - 1 through 8 (of 8 total)
- The topic ‘Customising cache Response Headers’ is closed to new replies.