DEV Community

Yaroslav Polyakov
Yaroslav Polyakov

Posted on • Edited on

apache2 allows CORS with credentials for any address

You cannot use '*' in Access-Control-Allow-Origin and use Access-Control-Allow-Credentials at same time. And this is actually makes sense, but during development this dirty hack is useful (for apache2):

SetEnvIf Origin "^http(s)?://.*$" REQUEST_ORIGIN=$0
Header always set Access-Control-Allow-Origin %{REQUEST_ORIGIN}e env=REQUEST_ORIGIN
Header always set Access-Control-Allow-Credentials true
Enter fullscreen mode Exit fullscreen mode

How it work in action (I'm using httpie instead of curl):

Example:

$ http -ph POST https://example.com/ Origin:https://google.com
HTTP/1.1 200 OK
Accept-Ranges: bytes
Access-Control-Allow-Credentials: true
Access-Control-Allow-Origin: https://google.com
Connection: Keep-Alive
Content-Encoding: gzip
Content-Length: 1039
Content-Type: text/html
Date: Thu, 12 Oct 2023 08:50:33 GMT
ETag: "9a1-6020521d58f80-gzip"
Keep-Alive: timeout=5, max=100
Last-Modified: Thu, 03 Aug 2023 13:55:26 GMT
Server: Apache/2.4.56 (Debian)
Strict-Transport-Security: max-age=31536000; includeSubDomains
Vary: Accept-Encoding
X-Content-Type-Options: nosniff
X-Frame-Options: disabled
Enter fullscreen mode Exit fullscreen mode

If you want it only for specific Origins:

    SetEnvIf Origin "^https?://(example.com|www.example.com)$" GOODORIGIN=$0
    Header set Access-Control-Allow-Origin %{GOODORIGIN}e env=GOODORIGIN
    Header set Access-Control-Allow-Credentials "true" env=GOODORIGIN
    Header merge Vary Origin
Enter fullscreen mode Exit fullscreen mode

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay