diff --git a/lib/moodlelib.php b/lib/moodlelib.php
index f6896ac..2034274 100644
--- a/lib/moodlelib.php
+++ b/lib/moodlelib.php
@@ -1898,11 +1898,11 @@ function require_login($courseorid=0, $autologinguest=true, $cm=null, $setwantsu
         } else {
             $loginguest = '';
         }
-        if (empty($CFG->loginhttps) or $loginguest) { //do not require https for guest logins
+        if (empty($CFG->loginhttps)) {
             redirect($CFG->wwwroot .'/login/index.php'. $loginguest);
         } else {
             $wwwroot = str_replace('http:','https:', $CFG->wwwroot);
-            redirect($wwwroot .'/login/index.php');
+            redirect($wwwroot .'/login/index.php'. $loginguest);
         }
         exit;
     }
diff --git a/login/index.php b/login/index.php
index e11a88f..fc24862 100644
--- a/login/index.php
+++ b/login/index.php
@@ -162,12 +162,15 @@ httpsrequired();
                        $user->id, 0, $user->id);
             $USER = complete_user_login($user);
 
+            if ((strpos($SESSION->wantsurl, $CFG->wwwroot) === 0) or (strpos($SESSION->wantsurl, $CFG->httpswwwroot) === 0)) {
+                $wantsurlpartofsite=true;
+            }
         /// Prepare redirection
             if (user_not_fully_set_up($USER)) {
                 $urltogo = $CFG->wwwroot.'/user/edit.php';
                 // We don't delete $SESSION->wantsurl yet, so we get there later
 
-            } else if (isset($SESSION->wantsurl) and (strpos($SESSION->wantsurl, $CFG->wwwroot) === 0)) {
+            } else if (isset($SESSION->wantsurl) and $wantsurlpartofsite ) {
                 $urltogo = $SESSION->wantsurl;    /// Because it's an address in this site
                 unset($SESSION->wantsurl);
 
