1

I want to redirect any request which is not an api call to the index method. All api urls start with "/api". Should I do this using mod_rewrite or can Flask handle this natively?

from flask import Flask

app = Flask(__name__, static_folder="public", static_url_path="")

@app.route("/", methods=["GET"])
def index():
    return render_template("index.html")

@app.route("/api/some_resources", methods=["GET"])
def get_all():
    pass
<VirtualHost *>
    ServerName example.com
    WSGIDaemonProcess my_app user=www-data group=www-data threads=5
    WSGIScriptAlias / /var/www/my_app/my_app.wsgi

    <Directory /var/www/my_app>
        WSGIProcessGroup my_app
        WSGIApplicationGroup %{GLOBAL}
        WSGIScriptReloading On
        Order deny,allow
        Allow from all
    </Directory>
</VirtualHost>
davidism
  • 121,510
  • 29
  • 395
  • 339
n00dl3
  • 21,213
  • 7
  • 66
  • 76
  • Do you mean any possible request, 404's included, or just several urls that you expect the user to have? – kylieCatt Aug 05 '15 at 16:04
  • any request that is not `/api/something` or my static files, but for the moment, Ifocus on `/api` – n00dl3 Aug 05 '15 at 16:06

1 Answers1

3

Create an error handler for 404 that will return a redirect rather than the 404 error if the path doesn't start with "/api". This way, the api can still 404 if someone accesses an endpoint that doesn't exist, but all other requests route to the index.

@app.errorhandler(404)
def handle_404(e):
    if request.path.startswith('/api'):
        return render_template('my_api_404.html'), 404
    else:
        return redirect(url_for('index'))
davidism
  • 121,510
  • 29
  • 395
  • 339