my scenario is composed by two webserver one local and one remote.
Local webserver (Apache) process a web app in which I want make an ajax request to remote webserver (Lighttpd).
Ajax request use angularjs $http.
var req = {
    method: 'POST',
    url: 'http://url/myphp.php',
    headers: {
        'Authorization': 'Basic ' + btoa('username:password'),
        'Content-Type': 'application/x-www-form-urlencoded'
    },
    xhrFields: {
       withCredentials: true
    },
    crossDomain: true,
    data: xmlString
}
$http(req).then(function () {
    console.log("OK!");
});
Remote php script is:
<?php
    echo "You have CORS!";
?>
Unfortunately I got a
401 Unhauthorized
XMLHttpRequest cannot load http://url/myphp.php. Response to    preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8888' is therefore not allowed access. The response had HTTP status code 401.
Remote web server has .htpasswd authentication mode enable and CORS request configured.
Follow a piece of lighttpd.conf
setenv.add-response-header = ( "Access-Control-Allow-Origin" => "*" )
                For add-response-header to work in lighttpd you must enable mod_setenv in your server.modules. However, you have to enable this mod_setenv before mod_status.
server.modules = (
    # ...
    "mod_fastcgi",
    "mod_rewrite",
    "mod_redirect",
    "mod_setenv", ## before mod_status
    "mod_status",
    # ...
)
Alternatively you could use PHP to output the cors header
<?php
header("Access-Control-Allow-Origin: *");
?>
I also want to add that if you are sending http basic/digest auth data you cannot use wildcards for the origin. You have to use the actual source domain
setenv.add-response-header = ( "Access-Control-Allow-Origin" => "example.com" )
setenv.add-response-header = ( "Access-Control-Allow-Credentials" => "true" )
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With