I am working on two separete ReactJS project which are both making use of the PHP API. Both react project are running from the dev server on port 3000 and one on 3001. Because the ReactJS on these ports are going to the API on port 80 its triggering a invalid CORS request so I got round this originally by adding the following to my Apache File:
Header set Access-Control-Allow-Origin: "http://localhost:3000"
I now want to set it up so that I can set different Access Control Allow Origins based on whether the request is coming from http://localhost:3000
and http://localhost:3001
.
I've tried the following but nothing I've tried seems to work:
<IfModule %{HTTP_REFERER} == "http://localhost:3001">
Header set Access-Control-Allow-Origin: "http://localhost:3001"
</IfModule>
<IfModule %{HTTP_REFERER} == "http://localhost:3000">
Header set Access-Control-Allow-Origin: "http://localhost:3000"
</IfModule>
But I get a CORS error stating that I've not specific an Access-Control-Allow-Origin header.
Is what I am trying to do possible and if so how I would I achieve what I am trying to do.
UPDATE
I've still been trying to figure this out, @ezra-s was right as I should have been using If not IfModule obviously but still not doing what I expect, so below is what I have now:
<If "%{HTTP_REFERER} == 'http://localhost:3001/'">
Header set Access-Control-Allow-Origin: "http://localhost:3001"
</If>
<If "%{HTTP_REFERER} == 'http://localhost:3000/'">
Header set Access-Control-Allow-Origin: "http://localhost:3000"
</If>
I've also updated the apache access log to show the referrer using the below log format:
LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\"" common
And I see this the below in the apache access log
::1 - - [15/Aug/2020:14:55:38 +0100] "POST /supportportal_api/admin-login.php HTTP/1.1" 500 5495 "http://localhost:3001/"
So although the referrer in the Apache access log is matching my If statement but I am still getting the following error in chrome:
Access to fetch at 'http://localhost/supportportal_api/admin-login.php' from origin 'http://localhost:3001' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
So it looks like for some reason my If statement isn't getting matched but can't see any reason why it wouldn't be.