Evgenii Legotckoi
Evgenii LegotckoiJan. 22, 2017, 3:05 a.m.

Django - Tutorial 019. Configuring the HTTPS protocol on the site of Let`s Encrypt

Yesterday I received a letter from Google , since I use Google Search Console to monitor the indexing of site in Google search engine. The essence of the letter is that Google Chrome will report unsafe site that uses the http protocol on pages that require a password. And when you consider that on my site authorization form located on every page, it means that a warning will be on all pages of the site. Not the most pleasant situation, so I had to quickly get an SSL certificate and configure https.

At the moment there CA Let`s Encrypt, which gives out free certificates for a period of 90 days. This CA is supported by organizations such as the Electronic Frontier Foundation (EFF), Mozilla Foundation, Akamai, Cisco Systems.

The process of obtaining and installing the certificate is automated, but in the case of a site that is running on Django and Nginx , will need further work on Nginx server settings.


Obtaining a certificate

To obtain a certificate and updates automatically using software Certbot software. The site Let`s encrypt refers to the software, where you can choose the type of your operating system and the server, which is used for the return of content on your site. In my case it Nginx and Ubuntu 16.04 .

There will be instruction on the installation and the process of obtaining the certificate.

To install the software certification use the following command:

sudo apt-get install letsencrypt 

Next, you must obtain a certificate by using the plugin webroot with the following command:

sudo letsencrypt certonly --webroot -w /var/www/example -d example.com -d www.example.com 

Where specified directory for the certification of your site, in this case /var/www/example , it will be necessary to create, and the corresponding domains for which you receive a certificate.

In this case, there a nuance. Already at this point you must configure Nginx , as in the directory /var/www/example will create a hidden directory .well-known , which is necessary to obtain a certificate. More information about the initial setup Nginx can read the corresponding article .

Therefore, pre-configure Nginx , as shown below and restart it.

server {
    listen 80;
    listen [::]:80;
    server_name example.com;

    location /.well-known {
        alias /var/www/example/.well-known;
    }

    location / {
        proxy_pass http://127.0.0.1:8000;
        proxy_set_header Host $server_name;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
}

Then you successfully get your SSL certificate.

Configuring https protocol

Once we have received the certificate, you must configure the https protocol, and for this you need to open port 443 on the server.

sudo ufw allow 443/tcp

And configure Nginx .

server {    
    listen 80;
    listen [::]:80;
    listen 443 ssl;
    listen [::]:443 ssl;
    server_name example.com;

    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;  

    location /.well-known {
        alias /var/www/example/.well-known;
    }

    location / {
        proxy_pass http://127.0.0.1:8000;
        proxy_set_header Host $server_name;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
}

In this case, specify the path to your certificates and the ports on which the server listens for connections.

Set up a connection via http

Leave it possible to connect via http protocol for users - it's up to you already, but what is the point to leave the opportunity to work on this protocol, if you already have https . Therefore, the user will do a redirect to the pages with http on the same page with https .

server {
    listen 80;
    listen [::]:80;
    server_name example.com;
    return 301 https://$server_name$request_uri;
}

server {
    listen 443 ssl;
    listen [::]:443 ssl;
    server_name example.com;

    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;  


    location /.well-known {
        alias /var/www/example/.well-known;
    }

    location / {
        proxy_pass http://127.0.0.1:8000;
        proxy_set_header Host $server_name;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
}

Restart Nginx and make sure that when you try to connect via http we automatically redirected to the connecting of https .

Automatic certificate renewal

Use the following command to update the certificate:

letsencrypt renew 

But the process can be automated using the cron (daemon designed to run jobs at a specific time or at regular intervals).

To edit cron as root execute the following command:

sudo crontab -e

It will provide the choice between the possible editors, choose your editor to taste. And I use nano. After that, insert the following line in the cron configuration.

30 2 * * 1 /usr/bin/letsencrypt renew >> /var/log/letsencrypt-renew.log

In this case, on Mondays at 2:30 am will be an attempt to renew the certificate.

Correction of content

The last thing left is the correction of all links on the site. That is, you need to change http to https, that the internal linking site does not create additional referrals.

For Django I recommend VDS-server of Timeweb hoster .

We recommend hosting TIMEWEB
We recommend hosting TIMEWEB
Stable hosting, on which the social network EVILEG is located. For projects on Django we recommend VDS hosting.

Do you like it? Share on social networks!

ArtDev
  • June 2, 2017, 2:58 p.m.

Добрый день хочу обновить сертификат, но получаю следующее

The following certs are not due for renewal yet: /etc/letsencrypt/live/mysite_ru/fullchain.pem (skipped) No renewals were attempted
. Как правильно обновить сертифика, подскажите? Может что в конфиге поправить?
Evgenii Legotckoi
  • June 3, 2017, 2:34 a.m.

Добрый день. Либо webroot не отработал как следует, либо вы где-то в настройке http накосячили. Смотрите строчки, где указывается путь к ssl сертификату в конфиге nginx.

Comments

Only authorized users can post comments.
Please, Log in or Sign up
г
  • ги
  • April 24, 2024, 3:51 a.m.

C++ - Test 005. Structures and Classes

  • Result:41points,
  • Rating points-8
l
  • laei
  • April 23, 2024, 9:19 p.m.

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:10points,
  • Rating points-10
l
  • laei
  • April 23, 2024, 9:17 p.m.

C++ - Тест 003. Условия и циклы

  • Result:50points,
  • Rating points-4
Last comments
k
kmssrFeb. 9, 2024, 7:43 a.m.
Qt Linux - Lesson 001. Autorun Qt application under Linux как сделать автозапуск для флэтпака, который не даёт создавать файлы в ~/.config - вот это вопрос ))
Qt WinAPI - Lesson 007. Working with ICMP Ping in Qt Без строки #include <QRegularExpressionValidator> в заголовочном файле не работает валидатор.
EVA
EVADec. 25, 2023, 11:30 p.m.
Boost - static linking in CMake project under Windows Ошибка LNK1104 часто возникает, когда компоновщик не может найти или открыть файл библиотеки. В вашем случае, это файл libboost_locale-vc142-mt-gd-x64-1_74.lib из библиотеки Boost для C+…
J
JonnyJoDec. 25, 2023, 9:38 p.m.
Boost - static linking in CMake project under Windows Сделал всё по-как у вас, но выдаёт ошибку [build] LINK : fatal error LNK1104: не удается открыть файл "libboost_locale-vc142-mt-gd-x64-1_74.lib" Хоть убей, не могу понять в чём дел…
G
GvozdikDec. 19, 2023, 10:01 a.m.
Qt/C++ - Lesson 056. Connecting the Boost library in Qt for MinGW and MSVC compilers Для решения твой проблемы добавь в файл .pro строчку "LIBS += -lws2_32" она решит проблему , лично мне помогло.
Now discuss on the forum
G
GarApril 22, 2024, 5:46 p.m.
Clipboard Как скопировать окно целиком в clipb?
DA
Dr Gangil AcademicsApril 20, 2024, 7:45 p.m.
Unlock Your Aesthetic Potential: Explore MSC in Facial Aesthetics and Cosmetology in India Embark on a transformative journey with an msc in facial aesthetics and cosmetology in india . Delve into the intricate world of beauty and rejuvenation, guided by expert faculty and …
a
a_vlasovApril 14, 2024, 6:41 p.m.
Мобильное приложение на C++Qt и бэкенд к нему на Django Rest Framework Евгений, добрый день! Такой вопрос. Верно ли следующее утверждение: Любое Android-приложение, написанное на Java/Kotlin чисто теоретически (пусть и с большими трудностями) можно написать и на C+…
Павел Дорофеев
Павел ДорофеевApril 14, 2024, 2:35 p.m.
QTableWidget с 2 заголовками Вот тут есть кастомный QTableView с многорядностью проект поддерживается, обращайтесь
f
fastrexApril 4, 2024, 4:47 p.m.
Вернуть старое поведение QComboBox, не менять индекс при resetModel Добрый день! У нас много проектов в которых используется QComboBox, в версии 5.5.1, когда модель испускает сигнал resetModel, currentIndex не менялся. В версии 5.15 при resetModel происходит try…

Follow us in social networks