Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Allowing cross origin requests for http and https

My website supports both http and https protocols. However using the code below in .htaccess file, I can only set one domain to allow CORS requests:

Header set Access-Control-Allow-Origin: http://example.com

I want to allow CORS for both http and https versions of my site (not just "*") and tried the solutions here: Access-Control-Allow-Origin Multiple Origin Domains?

But the problem is that all solutions rely on Origin header in the request which may not exist and also is not secure. (anyone can put a origin header in their request)

I want to know if the request has been served over https and use this info to set the proper CORS header. Something like this:

SetEnvIf servedOverHttps httpsOrigin=true
Header set Access-Control-Allow-Origin: https://example.me env=httpsOrigin

SetEnvIf notServedOverHttps httpOrigin=true
Header set Access-Control-Allow-Origin: http://example.me env=httpOrigin

How can I find out that it's a https request?

like image 449
LeoA Avatar asked Apr 18 '15 18:04

LeoA


People also ask

What is cross-origin http request?

Cross-Origin Resource Sharing (CORS) is an HTTP-header based mechanism that allows a server to indicate any origins (domain, scheme, or port) other than its own from which a browser should permit loading resources.

Does CORS work with https?

CORS requests may only use the HTTP or HTTPS URL scheme, but the URL specified by the request is of a different type. This often occurs if the URL specifies a local file, using the file:/// scheme.

How do you allow cross-origin?

Allow CORS: Access-Control-Allow-Origin lets you easily perform cross-domain Ajax requests in web applications. Simply activate the add-on and perform the request. CORS or Cross-Origin Resource Sharing is blocked in modern browsers by default (in JavaScript APIs).

How do I enable CORS in HTTP server?

For that, simply create a file simple-cors-http-server.py (or whatever) and, depending on the Python version you are using, put one of the following codes inside. Then you can do python simple-cors-http-server.py and it will launch your modified server which will set the CORS header for every response.


1 Answers

Have you tried using HTTPS variable?

It will be set to "on" for all https requests. Your .htaccess should look like this

Header set Access-Control-Allow-Origin: http://example.com             #default
Header set Access-Control-Allow-Origin: https://example.com env=HTTPS   #override if https
like image 181
advncd Avatar answered Sep 24 '22 15:09

advncd