2
votes

I have a single EC2 instance running behind ELB, for which I utilized AWS Certificate Manager (ACM) to enable HTTPS.

As suggested in a few places, I mapped both HTTP (Port 80) and HTTPS (443) to my instance's HTTP (Port 80).

I also enabled forcing secure connections by adding these lines to .htaccess file:

RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteCond %{HTTP:X-Forwarded-Proto} ^http$
RewriteRule .* https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

All that is working beautifully. All pages display secure content as expected, no warnings in the Console about mixed content.

Only on pages where I make an AJAX call I get an error about mixed content and only in Chrome. FireFox works as expected but Console still shows an error.

Error (FireFox):

Content Security Policy: Upgrading insecure request 'http://example.com/myapi/get_company/?code=abcd&limit=8' to use 'https'

Error (Chrome):

Mixed Content: The page at 'https://example.com/mypage' was loaded over HTTPS, but requested an insecure XMLHttpRequest endpoint 'http://example.com/myapi/get_company/?code=abcd&limit=8'. This request has been blocked; the content must be served over HTTPS.

I opened chrome://net-internals/ and from what I can see there are two calls the first one receives HTTP 301 Permanent Redirect and the second one fails because the redirect points to an HTTP page, not HTTPS.

AJAX call looks like this:

$url = "/myapi/get_company?code=" + e;
apiJson = $.ajax({
    url: $url, 
    dataType: 'json',
    data:{
        limit:8
    },
success: function(data) { //Some code here },
error: function(jqXHR, textStatus, errorThrown) { //Some code here }
});

I also tried giving the full URL including the protocol but that didn't make a difference.

3
Why do you need the condition RewriteCond %{HTTPS} !=on? - Shibashis

3 Answers

0
votes

Update .htaccess config

RewriteCond %{HTTPS} !=on --> Is not needed

update the .htaccess file config to

RewriteCond %{HTTP:X-Forwarded-Proto} !https RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301,NE]

Apart from changing .htaccess file you also need to ensure, once a page loads using HTTPS scheme, the ajax calls made from the page should not be on HTTP. The error you are seeing are browser errors and are isolated from how your elb is configured.

0
votes

I found a solution and now posting an answer to my own question. Don't ask me how I figured this out because I won't be able to give you a definite answer but this is what did it:

$url = "/myapi/get_company?code=" + e;

changed to:

$url = "/myapi/get_company/?code=" + e;

Notice the trailing slash, right before the parameters. The actual file handling the AJAX calls on the server side is here:

/myapi/get_company/index.php
0
votes

Check if the problem is on the server, not on the client. Your AJAX call is to an API endpoint; does that API endpoint return an HTTP redirect when it should return an HTTPS redirect?