PHP, Angular, HTACCESS - allow requests only from the origin domain
Get the solution ↓↓↓I finished my Angular project.
In my project I send POST requests with data to PHP files, and then get result from them back to Angular.
Now I want to allow requests only from the origin domain, and deny any request from any othe domain.
I try to use:
header("Access-Control-Allow-Origin: example.com");
but it does not work. And I don't want to use $_SERVER['HTTP_REFFER'] because it can manipulated. I also tried to use .HTACCESS but I don't know how to implement that. I tried something like that:
order deny, allow
deny from all
allow from mydomain.com
but it does not work.
My project already has the following .HTACCESS file:
RewriteEngine On
# If an existing asset or directory is requested go to it as it is
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -f [OR]
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -d
RewriteRule ^ - [L]
# If the requested resource doesn't exist, use index.html
RewriteRule ^ /index.html
taken from here: https://angular.io/guide/deployment#routed-apps-must-fallback-to-indexhtml
What can I do?
Thanks.
Answer
Solution:
Short answer :
header("Access-Control-Allow-Origin: *");
Is the minimum that should work (on your server side), but you may need to add two additional headers like:
header("Access-Control-Allow-Methods: POST, GET, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type");
Like anyheader()
call, be sure to perform those BEFORE any output.
Long answer:
CORS allow, with a relative security, to perform cross origin queries, depending on a pre-flight request OPTIONS to check what's allowed and what's not.
Access-Control-Allow-Origin
sets which origins (domains) are allowed. You may want to use only your trusted domains.
Access-Control-Allow-Methods
sets which methods are allowed. Usually, a lot of those.
Access-Control-Allow-Headers
sets which optional (and customized) headers are allowed. Usually, you want to include any non-standard headers on top of Content-type.
CORS is incredibly well documented here : https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: xmlhttprequest error flutter
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.