-2

I have an index page with two urls:

@app.route('/')
@app.route('/index')
def index():
    return render_template('index.html')

And when I go to https://localhost/ it works fine, but https://localhost/index is also valid. I want https://localhost/index to always redirect to https://localhost/ without having to doing something like this:

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/index')
def index_redirect():
    return redirect(url_for('index'))
zogs
  • 37
  • 5
  • I don't understand. If the first example works (and it does), what is the problem? – DeepSpace May 19 '21 at 18:37
  • can you explain what you mean by "redirect"? There's a specific meaning in HTTP terms, returning a 301 or 302 status code and sending back a new `location` but it sounds like that isn't what you want, so, what do you want? – Macattack May 19 '21 at 18:38

2 Answers2

0

When you say "without having to do something like this" - this is exactly what you'll need to do. If the first example is unacceptable, you'll need to simply redirect the browser to the URL that does work.

If you didn't want to have to hit the server twice, I suppose you could use Javascript's history.replaceState() to change the URL and get rid of the /index. But it's not something you can do from within Flask.

bnjab
  • 1
  • 2
0

I think flask.redirect is what you are looking for.

You can find the official documentation of flask.redirect here

You can also handle this at server level. following are the examples for uwsgi and nginx.