Reputation: 301
I am trying to redirect my 404 to a external URL like this:
@app.route('404')
def http_error_handler(error):
return flask.redirect("http://www.exemple.com/404"), 404
but it does not work. I keep getting:
Not Found The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.
Upvotes: 25
Views: 27527
Reputation: 65
Try this instead of a route
from flask import request
@app.errorhandler(404)
def own_404_page(error):
pageName = request.args.get('url')
print(pageName)
print(error)
f = open('erreur404.tpl')
return f.read()
Upvotes: 4
Reputation: 8978
You should try something like this:
from flask import render_template
@app.errorhandler(404)
def page_not_found(e):
return render_template('404.html'), 404
Source http://flask.pocoo.org/docs/1.0/patterns/errorpages/
Upvotes: 37
Reputation: 159875
You cannot do this - the user-agent (in most cases, a browser) looks at the status code that is returned to determine what to do. When you return a 404 status code what you are saying to the user-agent is, "I don't know what this thing is you are requesting" and the user-agent can then:
redirect
actually creates a little HTML response (via werkzeug.exceptions), which normally the end user doesn't see because the user-agent follows the Location
header when it sees the 302 response. However, you override the status code when you provide your own status code (404).
The fix is to either:
or Send a 404 with a meta:refresh
and / or JavaScript redirect (slightly better, still confusing):
return redirect("/where-ever"), 404, {"Refresh": "1; url=/where-ever"}
Upvotes: 6