Search code examples
.htaccessheaderapache2

.htaccess added Cors-headers are missing from time to time


Because the frontend runs on another port I have .htaccess file for development (no CORS in production, don't worry):

Header add Access-Control-Allow-Origin *
Header add Access-Control-Allow-Headers *
Header add Access-Control-Allow-Methods *

My app does the same backend-call several times. Sometimes after three or four of those (which went fine) suddenly the CORS-headers are missing from the call (and naturally CORS kicks in and the frontend doesn't get any response.).

Apparently the .htaccess file is ignored sometimes.

Apache-error log does not say anything.

Any idea what could cause this or how to debug?

  • FF 102.10.0esr
  • Chrome 113.0
  • Apache 2.4.56

Solution

  • Header add Access-Control-Allow-Origin *
    Header add Access-Control-Allow-Headers *
    Header add Access-Control-Allow-Methods *
    

    These headers will only be set on "successful" (ie. 2xx HTTP status) responses, since the default "condition" (or group of headers) is onsuccess. In other words, the above is the same as:

    Header onsuccess add Access-Control-Allow-Origin *
    Header onsuccess add Access-Control-Allow-Headers *
    Header onsuccess add Access-Control-Allow-Methods *
    

    (onsuccess is optional, since that is the default.)

    However, it would seem you are (erroneously) serving a 403 Forbidden response, so these headers are not being set (and you see a CORS error). In order to set the headers on both 2xx and non-2xx responses you need to use the always condition instead. For example:

    Header always add Access-Control-Allow-Origin *
    Header always add Access-Control-Allow-Headers *
    Header always add Access-Control-Allow-Methods *
    

    This can get a little confusing/messy. onsuccess and always (known as "conditions") are effectively two separate groups of headers. You can add a header to both groups and if you want to edit (or merge or unset) an existing header then you need to know in which group the header was initially set/added.

    Reference: