Intercambio de Recursos de Origen Cruzado: Cross-Origin Resource Sharing (CORS)

El Intercambio de Recursos de Origen Cruzado (Cross-Origin Resource Sharing, CORS) permite dar acceso a recursos del servidor desde otro dominio. Utilizando encabezados HTTP (Headers) podemos dar permiso a un user agent con un un origen distinto a nuetro dominio. Estas cabeceras podremos establecerlas directamente el en la configuración del servidor (Apache), mediante el fichero de configuración de carpetes de apache .htaccess o en las cabeceras de los phps.
CORS en .htaccess
<IfModule mod_headers.c>
<FilesMatch "\.(eot|ttf|otf|woff)">
Header set Access-Control-Allow-Origin "*"
</FilesMatch>
<FilesMatch "\.(eot|ttf|otf|woff|js|css)">
Header set Access-Control-Allow-Origin "http://www.ebay.com"
</FilesMatch>
</IfModule>
Con este ejemplo daremos acceso a nuestros ficheros de fuentes con extenxión .eot, .ttf, .otf y .wof, y limitamos el acceso a ficheros con extensión .js y .css a peticiones del dominios de www.ebay.com
Otros Headers para .htaccess:
Access-Control-Allow-Methods
The Access-Control-Allow-Methods header specifies the method or methods allowed when accessing the resource. This is used in response to a request.
Access-Control-Allow-Methods: "GET,POST,OPTIONS,DELETE,PUT"
Access-Control-Allow-Headers
The Access-Control-Allow-Headers header is used in response to a preflight request to indicate which HTTP headers can be used when making the actual request.
Access-Control-Allow-Headers: "DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,C$"
Access-Control-Allow-Credentials
The Access-Control-Allow-Credentials header Indicates whether or not the response to the request can be exposed when the credentials flag is true. When used as part of a response to a preflight request, this indicates whether or not the actual request can be made using credentials.
Access-Control-Allow-Credentials: true
Access-Control-Max-Age
The Access-Control-Max-Age header indicates how long the results of a preflight request can be cached. For an example of a preflight request, see the above examples.
Access-Control-Max-Age: 1728000
CORS on PHP
Si no podemos configurar apache podemos establecer la cabecera en el propio php usando la funcion "header" (que debe estar siempre presente antes de cualquier output):
<?php
header("Access-Control-Allow-Origin: *");
Referencias:
https://enable-cors.org/server_apache.html
https://developer.mozilla.org/es/docs/Web/HTTP/Access_control_CORS
https://www.html5rocks.com/en/tutorials/cors/