From d72b7c92690ad9f0cd93defaf059a708130693c3 Mon Sep 17 00:00:00 2001
From: Jaime Perez Crespo <jaime.perez@uninett.no>
Date: Fri, 3 Jun 2016 11:01:13 +0200
Subject: [PATCH] Fix an issue with some PHP environments (mostly related to
 FastCGI or php-fpm, common with nginx) where $_SERVER['SCRIPT_NAME'] is
 already populated with $_SERVER['PATH_INFO'] appended to it. In those cases,
 we should not blindly append PATH_INFO to SCRIPT_NAME, but check the latter
 first. This hopefully resolves #5 and closes #391.

---
 lib/SimpleSAML/Utils/HTTP.php | 10 +++++++++-
 www/module.php                | 12 +++++++++++-
 2 files changed, 20 insertions(+), 2 deletions(-)

diff --git a/lib/SimpleSAML/Utils/HTTP.php b/lib/SimpleSAML/Utils/HTTP.php
index b4613f1af..2251eee59 100644
--- a/lib/SimpleSAML/Utils/HTTP.php
+++ b/lib/SimpleSAML/Utils/HTTP.php
@@ -758,7 +758,15 @@ class HTTP
     {
         $url = self::getSelfURLHost();
         $url .= $_SERVER['SCRIPT_NAME'];
-        if (isset($_SERVER['PATH_INFO'])) {
+
+        /* In some environments, $_SERVER['SCRIPT_NAME'] already ends with $_SERVER['PATH_INFO']. Only append
+         * $_SERVER['PATH_INFO'] if it's set and missing from script name.
+         *
+         * Contributed by Travis Hegner.
+         */
+        if (isset($_SERVER['PATH_INFO']) &&
+            $_SERVER['PATH_INFO'] !== substr($_SERVER['SCRIPT_NAME'], - strlen($_SERVER['PATH_INFO'])))
+        {
             $url .= $_SERVER['PATH_INFO'];
         }
         return $url;
diff --git a/www/module.php b/www/module.php
index 9c09c6582..03409fe72 100644
--- a/www/module.php
+++ b/www/module.php
@@ -123,7 +123,17 @@ try {
 
     if (preg_match('#\.php$#D', $path)) {
         // PHP file - attempt to run it
-        $_SERVER['SCRIPT_NAME'] .= '/'.$module.'/'.$url;
+
+        /* In some environments, $_SERVER['SCRIPT_NAME'] is already set with $_SERVER['PATH_INFO']. Check for that case,
+         * and append script name only if necessary.
+         *
+         * Contributed by Travis Hegner.
+         */
+        $script = "/$module/$url";
+        if (stripos($_SERVER['SCRIPT_NAME'], $script) === false) {
+            $_SERVER['SCRIPT_NAME'] .= '/'.$module.'/'.$url;
+        }
+
         require($path);
         exit();
     }
-- 
GitLab