diff --git a/lib/SimpleSAML/Utilities.php b/lib/SimpleSAML/Utilities.php
index e6c80c4b3e01e8aa00a301daf31245aa55c8f663..6a902e092856a4fe9d649192e55743e7a5497440 100644
--- a/lib/SimpleSAML/Utilities.php
+++ b/lib/SimpleSAML/Utilities.php
@@ -2171,6 +2171,30 @@ class SimpleSAML_Utilities {
 			if (!isset($context['http']['request_fulluri'])) {
 				$context['http']['request_fulluri'] = TRUE;
 			}
+			// If the remote endpoint over HTTPS uses the SNI extension
+			// (Server Name Indication RFC 4366), the proxy could
+			// introduce a mismatch between the names in the
+			// Host: HTTP header and the SNI_server_name in TLS
+			// negotiation (thanks to Cristiano Valli @ GARR-IDEM
+			// to have pointed this problem).
+			// See: https://bugs.php.net/bug.php?id=63519
+			// These controls will force the same value for both fields.
+			// Marco Ferrante (marco@csita.unige.it), Nov 2012
+			if (preg_match('#^https#i', $path)
+				&& defined('OPENSSL_TLSEXT_SERVER_NAME')
+				&& OPENSSL_TLSEXT_SERVER_NAME) {
+				// Extract the hostname
+				$hostname = parse_url($path, PHP_URL_HOST);
+				if (!empty($hostname)) {
+					$context['ssl'] = array(
+						'SNI_server_name' => $hostname,
+						'SNI_enabled' => TRUE,
+						);
+				}
+				else {
+					SimpleSAML_Logger::warning('Invalid URL format or local URL used through a proxy');
+				}
+			}
 		}
 
 		$context = stream_context_create($context);