title: Routes With Custom Domains Using Flask
body: <p>My web app assigns a subdomain to users and optionally allows them to use a custom domain.  This works except when the user visits their custom domain for a route without including a trailing slash. </p>
  
  <p>GET requests to this url works as expected:  <code>http://user.example.com:5000/book/12345/</code></p>
  
  <p>GET requests to this url works as expected:  <code>http://custom.com:5000/book/12345/</code></p>
  
  <p>GET requests to this url attempt to redirect, but fail:  <code>http://custom.com:5000/book/12345</code></p>
  
  <p>Flask ends up redirecting the browser to this url which, of course, doesn't work:  <code>http://&lt;invalid&gt;.example.com:5000/book/12345/</code></p>
  
  <p>Is there a different way that I should handle custom domains?  Here's a complete minimal example to reproduce this.  I have set custom.com, example.com. and user.example.com to point to 127.0.0.1 in my /etc/hosts file in my development environment so that Flask receives the request.</p>
  
  <pre><code>from flask import Flask
  
  app = Flask(__name__)
  
  server = app.config['SERVER_NAME'] = 'example.com:5000'
  
  @app.route('/', subdomain="&lt;subdomain&gt;")
  @app.route('/')
  def index(subdomain=None):
  
      return ("index")
  
  @app.route('/book/&lt;book_id&gt;/', subdomain="&lt;subdomain&gt;")
  @app.route('/book/&lt;book_id&gt;/')
  def posts(post_id, subdomain=None):
  
      return (book_id)
  
  
  if __name__ == '__main__':
      app.run(host='example.com', debug=True)
  </code></pre>