diff --git a/lib/SimpleSAML/Utils/HTTP.php b/lib/SimpleSAML/Utils/HTTP.php
index a586ef8a47424d2592a202932e89037988ed57c5..612bf5c42a03bd43b18f4c381e762d7fff48651e 100644
--- a/lib/SimpleSAML/Utils/HTTP.php
+++ b/lib/SimpleSAML/Utils/HTTP.php
@@ -162,12 +162,14 @@ class HTTP
             Logger::warning('Redirecting to a URL longer than 2048 bytes.');
         }
 
-        // set the location header
-        header('Location: '.$url, true, $code);
+        if (!headers_sent()) {
+            // set the location header
+            header('Location: '.$url, true, $code);
 
-        // disable caching of this response
-        header('Pragma: no-cache');
-        header('Cache-Control: no-cache, must-revalidate');
+            // disable caching of this response
+            header('Pragma: no-cache');
+            header('Cache-Control: no-cache, must-revalidate');
+        }
 
         // show a minimal web page with a clickable link to the URL
         echo '<?xml version="1.0" encoding="UTF-8"?>'."\n";
@@ -178,7 +180,7 @@ class HTTP
         echo '    <meta http-equiv="content-type" content="text/html; charset=utf-8">'."\n";
         echo "    <title>Redirect</title>\n";
         echo "  </head>\n";
-        echo "  <body>\n";
+        echo "  <body onload=\"window.location.replace('".htmlspecialchars($url)."');\">\n";
         echo "    <h1>Redirect</h1>\n";
         echo '      <p>You were redirected to: <a id="redirlink" href="'.htmlspecialchars($url).'">';
         echo htmlspecialchars($url)."</a>\n";