enable cors in .htaccess

215,301

Solution 1

Since I had everything being forwarded to index.php anyway I thought I would try setting the headers in PHP instead of the .htaccess file and it worked! YAY! Here's what I added to index.php for anyone else having this problem.

// Allow from any origin
if (isset($_SERVER['HTTP_ORIGIN'])) {
    // should do a check here to match $_SERVER['HTTP_ORIGIN'] to a
    // whitelist of safe domains
    header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
    header('Access-Control-Allow-Credentials: true');
    header('Access-Control-Max-Age: 86400');    // cache for 1 day
}
// Access-Control headers are received during OPTIONS requests
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {

    if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
        header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");         

    if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
        header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");

}

credit goes to slashingweapon for his answer on this question

Because I'm using Slim I added this route so that OPTIONS requests get a HTTP 200 response

// return HTTP 200 for HTTP OPTIONS requests
$app->map('/:x+', function($x) {
    http_response_code(200);
})->via('OPTIONS');

Solution 2

Should't the .htaccess use add instead of set?

Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Methods: "GET,POST,OPTIONS,DELETE,PUT"

Solution 3

This is what worked for me:

Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Headers "origin, x-requested-with, content-type"
Header add Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"

Solution 4

As in this answer Custom HTTP Header for a specific file you can use <File> to enable CORS for a single file with this code:

<Files "index.php">
  Header set Access-Control-Allow-Origin "*"
  Header set Access-Control-Allow-Methods: "GET,POST,OPTIONS,DELETE,PUT"
</Files>

Instead of "*" you can put specific origin (protocol + domain+ optional port).

Solution 5

Will be work 100%, Apply in .htaccess:

# Enable cross domain access control
SetEnvIf Origin "^http(s)?://(.+\.)?(1xyz\.com|2xyz\.com)$" REQUEST_ORIGIN=$0
Header always set Access-Control-Allow-Origin %{REQUEST_ORIGIN}e env=REQUEST_ORIGIN
Header always set Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS"
Header always set Access-Control-Allow-Headers "x-test-header, Origin, X-Requested-With, Content-Type, Accept"

# Force to request 200 for options
RewriteEngine On
RewriteCond %{REQUEST_METHOD} OPTIONS
RewriteRule .* / [R=200,L]
Share:
215,301
Devin Crossman
Author by

Devin Crossman

Updated on September 28, 2021

Comments

  • Devin Crossman
    Devin Crossman over 2 years

    I have created a basic RESTful service with the SLIM PHP framework and now I'm trying to wire it up so that I can access the service from an Angular.js project. I have read that Angular supports CORS out of the box and all I needed to do was add this line: Header set Access-Control-Allow-Origin "*" to my .htaccess file.

    I've done this and my REST application is still working (no 500 internal server error from a bad .htaccess) but when I try to test it from test-cors.org it is throwing an error.

    Fired XHR event: loadstart
    Fired XHR event: readystatechange
    Fired XHR event: error
    
    XHR status: 0
    XHR status text: 
    Fired XHR event: loadend
    

    My .htaccess file looks like this

    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ /index.php [QSA,L]
    Header set Access-Control-Allow-Origin "*"
    Header set Access-Control-Allow-Methods: "GET,POST,OPTIONS,DELETE,PUT"
    

    Is there something else I need to add to my .htaccess to get this to work properly or is there another way to enable CORS on my server?

  • BBog
    BBog over 10 years
    Thank you! this solved my problem! I was using set and it didn't work, changing it with add fixed it. For what it's worth, this was done on a wordpress blog, with some other stuff in the .htaccess file as well
  • raph77777
    raph77777 over 7 years
    You save four lives so far, even thought I only needed header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}"); . Thank you !
  • Ryan How
    Ryan How over 7 years
    The documentation here says "set" enable-cors.org/server_apache.html . Probably caused a lot of issues!
  • Sushivam
    Sushivam about 7 years
    I changed from set to add and still get Response for preflight has invalid HTTP status code 400 ..pls suggest..have described my full post here: magento.stackexchange.com/questions/170342/…
  • Joe
    Joe almost 6 years
    Having reviewed the other answer, I have a concern about your solution. The author slashingweapon included a comment that you removed that prompted you to add in some logic to decide if the origin was a trusted origin. Here you've blindly removed it, accepting any origin. Not good practice.
  • Devin Crossman
    Devin Crossman almost 6 years
    @Joe good point. I updated the answer with a comment about checking the origin
  • user1298923
    user1298923 over 4 years
    Would just like to add that it is necessary to edit the SetEnvIf statement, defining which remotes (1xyz.com, 2xyz.com) are allowed CORS.
  • kslstn
    kslstn over 4 years
    For me the first line sufficed. Also, I guess the second line should not have a colon?
  • DrLightman
    DrLightman over 3 years