1

How can I redirect HTTP to HTTPS by default?

For example, if I type example_address.com I would like to get https://example_address.com

My code is below

def run(server_class=HTTPServerV6, handler_class=Server, port=443):
    server_address = ('::', port)
    httpd = server_class(server_address, handler_class)
    httpd.socket = ssl.wrap_socket (httpd.socket, certfile='./secret_private_key.pem', server_side=True)
    try:
        httpd.serve_forever()
    except KeyboardInterrupt:
        pass
    httpd.server_close()
4
  • Why do you want to do this? If you're hosting an actual website with an https endpoint and a certificate, you should use an actual server. Commented Jun 17, 2018 at 20:16
  • Can you please explain your thought? When I am connecting to the server, I have to write https. So, my desire is to avoid that process. Commented Jun 17, 2018 at 20:18
  • Let me know if you want to add .htaacess url redirect rule ?? Basically it will redirect user to https version whenever they open any url in http version. Commented Jun 18, 2018 at 9:53
  • I cannot find how to use htacces in python. My server uses only python. Commented Jun 18, 2018 at 11:15

1 Answer 1

2

You could try running another server in port 80 and redirecting its requests to your https server.

Something like this:

def runHTTP(server_class=HTTPServerV6, handler_class=Server, port=80):
server_address = ('::', port)
httpd = server_class(server_address, handler_class)
httpd.send_response(301)
httpd.send_header('Location','https://www.yourserver.com')
httpd.end_headers()
Sign up to request clarification or add additional context in comments.

1 Comment

This approach has its place. I have a piece of stand alone software that has it's own webserver embedded on 443. This provides a very simple redirect w/o having to stand up nginx or apache.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.