title: Canonicalize URLs for static site with custom domain in GAE
body: <p>I'm running a static site on GAE and using a custom domain (let's call it <code>example.com</code>) with SSL certificates enabled. I'd like to canonicalize URLs to <code>https://www.example.com/</code>. That means catching any requests to <code>myproject.appspot.com</code>, plain HTTP, and/or the naked domain, and redirecting to <code>www</code> over HTTPS.</p>
  
  <p>I understand that it's not possible to put redirect logic in <code>app.yaml</code>, but ideally I'd like to keep the static file serving logic there, and only have app code for the redirect. (As opposed to doing the static serving in app code as well.)</p>
  
  <p>Here's what I have so far:</p>
  
  <p>Contents of the file <code>app.yaml</code>:</p>
  
  <pre><code>runtime: python27
  api_version: 1
  threadsafe: true
  
  handlers:
  - url: /
    static_files: www/index.html
    upload: www/index.html
  
  - url: /(.*)
    static_files: www/\1
    upload: www/(.*)
  </code></pre>
  
  <p>Contents of the file <code>dispatch.yaml</code>:</p>
  
  <pre><code>dispatch:
  - url: "myproject.appspot.com/*"
    module: canonicalizer
  </code></pre>
  
  <p>Contents of the file <code>canonicalizer.yaml</code>:</p>
  
  <pre><code>module: canonicalizer
  runtime: python27
  api_version: 1
  threadsafe: true
  
  handlers:
  - url: /.*
    script: canonicalizer.app
  </code></pre>
  
  <p>Contents of the file <code>canonicalizer.py</code>:</p>
  
  <pre><code>import webapp2
  
  def get_redirect_uri(handler, *args, **kwargs):
      return 'https://www.example.com/' + kwargs.get('path')
  
  app = webapp2.WSGIApplication([
      webapp2.Route('/&lt;path:.*&gt;',
      webapp2.RedirectHandler,
      defaults={'_uri': get_redirect_uri, '_code': 302}),
  ], debug=True)
  </code></pre>
  
  <p>As you can see, I've only attempted to implement redirecting <code>myproject.appspot.com</code> so far. I haven't been able to get it working; <code>myproject.appspot.com</code> still serves content rather than redirecting to the custom domain.</p>
  
  <p>I saw <a href="https://stackoverflow.com/questions/32671890/redirect-all-requests-from-one-domain-to-another-with-google-app-engine-but-keep">a similar SO question</a> and used it as a basis for my code above. I followed it fairly closely, so I'm not sure if it's outdated or missing details.</p>
  
  <p>I'm not very familiar with webapp2. Also open to solutions in a different framework or even different programming language.</p>