I'm using a 307 redirect mod_rewrite
rule in my .htaccess
to redirect all /api/...
requests to an apiHandler.php
, and I'm having trouble with CORS.
My .htaccess
RewriteEngine On
RewriteRule ^api/(.*)$ /apiHandler.php [NC,R=307]
My apiHandler.php
<?php
header("Access-Control-Allow-Origin: http://localhost:4200");
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Allow-Headers: Content-Type");
header("Content-Type: application/json");
...
?>
Whenever I make an api request in my front-end, I get a CORS error,
"...has been blocked by CORS policy: No 'Access-Control-Allow-Origin` header is present on the request resource."
yet I specifically have that header in my apiHandler.php
, so I don't know what the issue is.
After doing a little bit of research, I've heard that the redirecting URL must also include an Access-Control-Allow-Origin
header, or else the browser will stop right there with its attempted cross-domain request. But I've already tried also adding those headers to my .htaccess
with no luck.
Any ideas?
Thank you @sideshowbarker! The solution to my problem was removing the headers from my apiHandler.php
and adding them to my .htaccess
.
Header always set Access-Control-Allow-Origin "http://localhost:4200"
Header always set Access-Control-Allow-Credentials "true"
Header always set Access-Control-Allow-Headers "Content-Type"
Header always set Content-Type "application/json"
RewriteEngine On
RewriteRule ^api/(.*)$ /apiHandler.php [NC,R=307]
Notice the use of Header always set ...
instead of Header set ...
. This post explains the difference between the two.