簡體   English   中英

阻止來自* .appspot.com的請求並在Google App Engine中強制自定義域

[英]Block requests from *.appspot.com and force custom domain in Google App Engine

如何阻止用戶訪問example.appspot.com上的應用並強制他們在example.com上訪問它? 我已經有example.com工作,但我不希望用戶能夠訪問appspot域。 我正在使用python。

您可以檢查os.environ['HTTP_HOST'].endswith('.appspot.com') - 如果是,那么您從something.appspot.com提供服務並可以發送重定向,或以其他方式改變您的行為期望。

您可以以各種方式(裝飾器,WSGI中間件,從您的中間基類繼承webapp.RequestHandler [[或任何其他方式])部署此檢查和重定向(如果需要)(或您選擇的其他行為更改)您正在使用的其他基本處理程序類]]和方法名稱與您的應用程序級別處理程序類中的get和post不同,但我認為這里的關鍵思想是os.environ由app引擎設置根據CGI標准的框架,因此您可以依賴這些標准(類似地,WSGI基於它從os.environ中獲取的值構建自己的環境)。

上面發布的代碼有兩個問題 - 它嘗試重定向安全流量(自定義域不支持),當Google在您的appspot域上調用它們並且您提供301時,您的cron作業也會失敗。

我在我的博客上發布了一個略微修改過的版本: http//blog.dantup.com/2009/12/redirecting-requests-from-appid-appspot-com-to-a-custom-domain

為方便起見,我已經包含了以下代碼。

from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app

def run_app(url_mapping):
    application = webapp.WSGIApplication(url_mapping, debug=True)
    application = redirect_from_appspot(application)
    run_wsgi_app(application)

def redirect_from_appspot(wsgi_app):
    """Handle redirect to my domain if called from appspot (and not SSL)"""
    from_server = "dantup-blog.appspot.com"
    to_server = "blog.dantup.com"

    def redirect_if_needed(env, start_response):

        # If we're calling on the appspot address, and we're not SSL (SSL only works on appspot)
        if env["HTTP_HOST"].endswith(from_server) and env["HTTPS"] == "off":

            # Parse the URL
            import webob, urlparse
            request = webob.Request(env)
            scheme, netloc, path, query, fragment = urlparse.urlsplit(request.url)
            url = urlparse.urlunsplit([scheme, to_server, path, query, fragment])

            # Exclude /admin calls, since they're used by Cron, TaskQueues and will fail if they return a redirect
            if not path.startswith('/admin'):
                # Send redirect
                start_response("301 Moved Permanently", [("Location", url)])
                return ["301 Moved Peramanently", "Click Here %s" % url]

        # Else, we return normally
        return wsgi_app(env, start_response)

    return redirect_if_needed
def redirect_from_appspot(wsgi_app):
def redirect_if_needed(env, start_response):
    if env["HTTP_HOST"].startswith('my_app_name.appspot.com'):
        import webob, urlparse
        request = webob.Request(env)
        scheme, netloc, path, query, fragment = urlparse.urlsplit(request.url)
        url = urlparse.urlunsplit([scheme, 'www.my_domain.com', path, query, fragment])
        start_response('301 Moved Permanently', [('Location', url)])
        return ["301 Moved Peramanently",
              "Click Here" % url]
    else:
        return wsgi_app(env, start_response)
return redirect_if_needed  

您可以通過以下方式覆蓋webapp2.RequestHandler基類中的initialize方法,將其重定向到您的自定義域(此處為example.com ):

def initialize(self, *a, **kw):
    webapp2.RequestHandler.initialize(self, *a, **kw)

    if self.request.host.endswith('appspot.com'):
        self.request.host = 'example.com'
        self.redirect(self.request.url, permanent=True)

如果您使用的是webapp2 ,可以使用其DomainRoute稍微簡單一些(取決於您的用例)解決方案。

如果這是您的URL地圖:

url_map = [
    ('/', HomeHandler),
    ('/about', AboutHandler),
    ('/admin/(.+)', AdminHandler),
    MailForwardHandler.mapping(),
]
application = webapp2.WSGIApplication(url_map, debug=True)

和管理員和郵件應該重定向,然后添加重定向路線如下:

from webapp2_extras import routes

url_map = [
    routes.DomainRoute('appid.appspot.com', [
        routes.RedirectRoute('/', redirect_to='http://app.com', schemes=['http']),
        routes.RedirectRoute('/about', redirect_to='http://app.com/about', schemes=['http']),
    ],
    ('/', HomeHandler),
    ('/about', AboutHandler),
    ('/admin/(.+)', AdminHandler),
    MailForwardHandler.mapping(),
]
application = webapp2.WSGIApplication(url_map, debug=True)

根據規定,這將僅重定向http, 而不是 https。 它根據需要使用永久重定向(301)。

您還可以將函數傳遞給redirect_to如文檔中所述 ,這可以使您在擁有大量規則時更容易。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM