Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force https via .htaccess with one post http url exception made using fetch

I am able to force https for a domain using this code:

RewriteEngine On
RewriteCond %{ENV:HTTPS} !on
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

RewriteRule ^index.html$ / [L,R=301]

RewriteCond %{THE_REQUEST} /([^.]+)\.html [NC]
RewriteRule ^ /%1 [L,R]
RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule ^(.*?)/?$ /$1.html [L]

ErrorDocument 404 /404.html

Now I need to make a get request to a strictly http url using fetch jquery using

fetch('http://universities.hipolabs.com/search?country=canada')           //api for the get request
  .then(response => response.json())
  .then(data => showUnis(data) );

How do i add this exception to the .htaccess file so the get request can work? Any help is appreciated in advance.

like image 483
vin shaba Avatar asked Nov 23 '25 15:11

vin shaba


1 Answers

Ideally, you would be sending a custom HTTP request header as part of your client-side JavaScript request. For example, if you are sending the HTTP request header JavaScript-Request: 1 then in your redirect rule in .htaccess it is straight forward to make an exception. For example:

RewriteCond %{ENV:HTTPS} !on
RewriteCond %{HTTP:JavaScript-Request} !1
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

Then, to make an exception for any other URLs you just need to make sure you are sending the appropriate HTTP request header as part of the request.

Otherwise, you would need to make an exception for this specific URL (and anyone making a request to this URL in their browser will also be excluded from the redirect).

For example:

RewriteCond %{ENV:HTTPS} !on
RewriteCond %{THE_REQUEST} !\s/search\?country=canada\s
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

You'll need to clear your browser cache before testing (since 301s are cached persistently by the browser). Test first with 302 (temporary) redirects to avoid potential caching issues.

HOWEVER, this is likely to trigger an insecure browser warning when the initial insecure HTTP request is made and the browser is likely to block the request anyway. Realistically, you need to be HTTPS everywhere.

like image 70
MrWhite Avatar answered Nov 25 '25 05:11

MrWhite