瀏覽代碼

[fix] reverse proxy non-root url fix

Adam Tauber 9 年之前
父節點
當前提交
6ef7c3276c
共有 1 個文件被更改,包括 37 次插入2 次删除
  1. 37
    2
      searx/webapp.py

+ 37
- 2
searx/webapp.py 查看文件

@@ -781,10 +781,45 @@ def run():
781 781
     )
782 782
 
783 783
 
784
-application = app
784
+class ReverseProxyPathFix(object):
785
+    '''Wrap the application in this middleware and configure the
786
+    front-end server to add these headers, to let you quietly bind
787
+    this to a URL other than / and to an HTTP scheme that is
788
+    different than what is used locally.
789
+
790
+    http://flask.pocoo.org/snippets/35/
791
+
792
+    In nginx:
793
+    location /myprefix {
794
+        proxy_pass http://127.0.0.1:8000;
795
+        proxy_set_header Host $host;
796
+        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
797
+        proxy_set_header X-Scheme $scheme;
798
+        proxy_set_header X-Script-Name /myprefix;
799
+        }
800
+
801
+    :param app: the WSGI application
802
+    '''
803
+    def __init__(self, app):
804
+        self.app = app
805
+
806
+    def __call__(self, environ, start_response):
807
+        script_name = environ.get('HTTP_X_SCRIPT_NAME', '')
808
+        if script_name:
809
+            environ['SCRIPT_NAME'] = script_name
810
+            path_info = environ['PATH_INFO']
811
+            if path_info.startswith(script_name):
812
+                environ['PATH_INFO'] = path_info[len(script_name):]
813
+
814
+        scheme = environ.get('HTTP_X_SCHEME', '')
815
+        if scheme:
816
+            environ['wsgi.url_scheme'] = scheme
817
+        return self.app(environ, start_response)
785 818
 
786
-app.wsgi_app = ProxyFix(application.wsgi_app)
787 819
 
820
+application = app
821
+# patch app to handle non root url-s behind proxy & wsgi
822
+app.wsgi_app = ReverseProxyPathFix(ProxyFix(application.wsgi_app))
788 823
 
789 824
 if __name__ == "__main__":
790 825
     run()