[#7787] get rid of weird problems where error handling and ssl redirects collide
diff --git a/Allura/allura/lib/custom_middleware.py b/Allura/allura/lib/custom_middleware.py
index 1116b45..8212cd2 100644
--- a/Allura/allura/lib/custom_middleware.py
+++ b/Allura/allura/lib/custom_middleware.py
@@ -168,21 +168,26 @@
         if self._no_redirect_re.match(environ['PATH_INFO']):
             return req.get_response(self.app)(environ, start_response)
         resp = None
+
         try:
             request_uri = req.url
             request_uri.decode('ascii')
         except UnicodeError:
             resp = exc.HTTPNotFound()
+
         secure = req.url.startswith('https://')
         srv_path = req.url.split('://', 1)[-1]
         # allura-loggedin is a non-secure cookie as a flag to know that the user has a session over on https
         force_ssl = (self._force_ssl_logged_in and req.cookies.get('allura-loggedin')) \
                     or self._force_ssl_re.match(environ['PATH_INFO'])
-        if not secure and force_ssl:
+        if req.environ.get('pylons.original_request'):
+            # if an error occurs, then /error/document is fetched (denoted by pylons.original_request)
+            # and we don't want to do any redirects within that sub-request
+            pass
+        elif not secure and force_ssl:
             resp = exc.HTTPFound(location='https://' + srv_path)
         elif secure and not force_ssl:
             resp = exc.HTTPFound(location='http://' + srv_path)
-
         if not resp:
             resp = self.app
         return resp(environ, start_response)
diff --git a/Allura/allura/tests/functional/test_root.py b/Allura/allura/tests/functional/test_root.py
index 179f19a..8f29b31 100644
--- a/Allura/allura/tests/functional/test_root.py
+++ b/Allura/allura/tests/functional/test_root.py
@@ -166,3 +166,17 @@
             assert_equal(arg.undecorated,
                          NeighborhoodController.index.undecorated)
             set_transaction_name.assert_called_with('foo')
+
+
+class TestRootWithSSLPattern(TestController):
+    def setUp(self):
+        with td.patch_middleware_config({'force_ssl.pattern': '^/auth'}):
+            super(TestRootWithSSLPattern, self).setUp()
+
+    def test_no_weird_ssl_redirect_for_error_document(self):
+        # test a 404, same functionality as a 500 from an error
+        r = self.app.get('/auth/asdfasdf',
+                         extra_environ={'wsgi.url_scheme': 'https'},
+                         status=404)
+        assert '302 Found' not in r.body, r.body
+        assert '/error/document' not in r.body, r.body