2

I keep finding answers on how to read a redirect from an HTTP client response out of Python, but I can't figure out how to send a 301 or 302 redirect back to the client. Seems this should work, but I always get a 200 response before the body:

print("Content-Type: text/html; charset=UTF-8\n")
print("HTTP/1.1 301 Moved Permanently")
print("Location:", "https://www.google.com/")

The equivalent PHP code would simply be:

// Redirect the browser to Google
header("Location: https://www.google.com/", true, 301);
John Heyer
  • 711
  • 1
  • 6
  • 18

1 Answers1

0

In it's simplest form, with no external libraries, you can simply output straight HTTP:

print('''Status: 301 Redirect
Location: {url}
Content-Type: text/html

Moved permanently to <a href="{url}">{url}</a>
'''.format(url='https://www.google.com/'))

If you are using a library or framework there are likely better approaches.

codnodder
  • 1,674
  • 9
  • 10