Nikita
Nikita

Reputation: 495

Taking django application to https

I have a django application running perfectly fine in development server with http://localhost:8081

I need to take it to https. For which I tried 2 methods, but none of them is working.

Method1: Using stunnel

I installed stunnel and generated cert and key with openssl.

openssl genrsa 2048 > ca.key
openssl req -new -x509 -nodes -sha1 -days 365 -key ca.key > ca.cert
cat ca.key ca.cert > ca.pem

Defined dev_https as:

pid=

cert = certs/ca.pem
sslVersion = all
foreground = yes
output = stunnel.log

[https]
accept=10443
connect=8081

and executed below commands:

stunnel certs/dev_https &
HTTPS=on /home/user/python3.9/bin/python3 /path/to/django/app/manage.py runserver localhost:8081

This is giving me error on console from stunnel as:

connect_blocking: connect 127.0.0.1:8081: Connection refused (111)
Connection reset: 0 byte(s) sent to SSL, 0 byte(s) sent to socket

from django app gui:

If I try to access the app over https://localhost:10443

This site can’t be reached

If I try to access app over http://localhost:8081 ---> It works fine. But that's not required.

Method2: Apache with mod_wsgi

I installed mod_wsgi with rpm. Then modified httpd.conf as:

LoadModule wsgi_module modules/mod_wsgi.so

WSGIScriptAlias / /path/to/django/app/wsgi.py
WSGIPythonHome /home/user/python3.9
WSGIPythonPath "/home/user/python3.9/lib;/home/user/python3.9/lib/python3.9/site-packages"

<Directory /path/to/django/app>
<Files wsgi.py>
Require all granted
</Files>
</Directory>

and restarted the httpd.

On starting the django app with

HTTPS=on /home/user/python3.9/bin/python3 /path/to/django/app/manage.py runserver localhost:8081

gives no error on console but app is still not accessible over https.

Any help would be appreciated

Upvotes: 0

Views: 2386

Answers (1)

PatDuJour
PatDuJour

Reputation: 975

The default Django manage.py runserver command doesn't support SSL, that's probably why method 1 doesn't work for you.

Check out django-extension package.

  1. Install django-extensions with Werkzeug Werkzeug is required for runserver_plus which is what we will use
pip install django-extensions Werkzeug
  1. Add django_extensions to the INSTALLED_APPS
INSTALLED_APPS = [
    # ...
    "django_extensions",
]
  1. start the local development server in HTTPS mode with the cert & key you generated from OpenSSL
python manage.py runserver_plus --cert-file cert.pem --key-file key.pem

Upvotes: 0

Related Questions