投稿日: | 最終更新日:
Djnago+ApacheサーバにLet’s Encryptで証明書を発行する
ConoHaVPSにセットアップしたDjangoをhttps化します。そのため、Let’s Encryptを使用します。
Let’s Encryptとは?
Let’s Encryptは、認証局(CA)として「SSL/TLSサーバ証明書」を無料で発行します。Let’s Encryptは、証明書の発行・インストール・更新のプロセスを自動化することにより、TLSやHTTPS(TLSプロトコルによって提供されるセキュアな接続の上でのHTTP通信)を普及させることを目的としているプロジェクトです。2016年4月12日 に正式サービスが開始されました。無料のet’s Encrypt が発行する SSL/TLS サーバ証明書を利用するには、certbotというアプリケーションを使用します。
CentOS7では、certbotを利用します。
certbotで証明書の発行の問題点
通常なら以下コマンドを実行すれば、Webサイトのルートディレクトリに証明書などのファイルが生成されます。
certbot-auto certonly --webroot -w /path/to/webroot -d domainname --email=xxxx@sample.com
Djangoの場合は 「–webroot -w /path/to/webroot 」が問題となります。このコマンドは、certbotコマンドが指定したドメイン直下にファイルを生成し、そこにアクセスを試みることでサイトの管理者を確認するという方法を取っているためです。
Djangoでは、html, css, jpg のような静的ファイルに対して以下のようなパスを割り当てます。
{project root}/static/
そしてその静的ファイルにアクセスするには 「https://独自ドメイン/static/{any_file} などにする必要があります。しかし、上記コマンドでアクセスするディレクトリは、以下のURLとなります。
/.well-known/acme-challenge/{token}
このコマンドでは、 404 が返ってしまいます。
Djangoでは証明書の読み込むには?
Djangoは静的ファイルをそのまま配信することができません。そのため、Webアプリケーション内に証明書ファイルの置き場所を指定する記述が必要です。
作業の流れ
- Certbotクライアントをインストールする
- Apacheのバーチャルホスト設定
- settings.pyの設定
- Djangoプロジェクト内urls.pyの設定
- Apacheの設定ファイルssl.confにバーチャルホストの設定
- httpsサービス・443ポートの開放
- SSL/TLS証明書の作成
前提条件
今回の作業を行うにあたり、以下の前提条件を満たしているとします。
- すでにDjango サイトが動いている状態
- すでにDjangoプロジェクトの静的ファイル設置場所を指定している
- Web サーバに Apache を使っていること
準備
以下の準備を行います。
ConoHaVPSの準備
①ConoHaをレンタルします。
②ConoHaにroot以外のユーザを作ります。
③ConoHaにSSH接続するための設定を行います。
④ConoHaへのrootログインを禁止します。
⑤ConoHaのportを22から変更します。
⑥ConoHaVPSへApacheをインストールしてスタートページを表示します。
Python・Djangoの準備
①ConoHaVPSへPython3をインストールします。
②ConoHaVPSへPython3をインストールします。
③ConoHaVPSへWSGIをインストールします。
→ConoHaのVPSにApacheでPythonWebアプリを作る(WSGI)
④ConoHaVPSへDjangoをインストールします。
⑤Djangoのデータベース接続・初期化します。
⑥Djangoのプロジェクトにアプリケーションを作成します。
必要なもの
レンタルサーバ | ConoHaのVPSサーバ |
---|---|
独自ドメイン | ムームードメインで、独自ドメインのみ取得。2年契約で(2,000〜3,000円)くらい? |
ConoHaVPSの環境
アプリケーションサーバ OS | CentOS7.4 |
---|---|
Apache | 2.4.6 (CentOS) |
Python | 3.6.4 |
mod-wsgi | 4.5.24 |
Django | 2.0.2 |
mysqlclient | 1.3.12 |
PyMySQL | 0.8.0 |
クライアントPC
操作開発用のクライアントPCを用意します。windowsでもmacでも可能ですが、今回はubuntuを利用します。
OS | Ubuntu 16.04.1 LTS 64bit |
---|
Certbotクライアントをインストールする
すでにtest_djangoプロジェクトが作成済みとします。今回はtest_djangoプロジェクトに、pollsアプリケーションを作成します。
プロジェクト名 | test_django |
---|---|
アプリケーション名 | polls |
CentOS 7 用の Certbot クライアントは、EPELリポジトリからインストールすることができます。
①VPSにログインします。
②前回作った仮想環境を起動します。
cd . test_django/bin/activate
③後ほどCertbotを利用しますので、root権限にログインします。
su -
③epelリポジトリをインストールします。
sudo yum install epel-release
④certbotとpython-certbot-apacheをインストールします。
sudo yum install certbot python-certbot-apache
Apacheのバーチャルホスト設定
前回までは、直接httpd.confファイル(Apacheの設定ファイル)にドキュメントルートやWSGIモジュールのリンクを記述していました。しかし、今回からバーチャルホストを設定し、DjangoWebアプリケーションの設定情報を「wsgi.conf」ファイルへ分割します。
変更前
- /etc/httpd/conf/
- httpd.conf
- magic
- /etc/httpd/conf.d/
- autoindex.conf
- ssl.conf
- userdir.conf
- welcome.conf
変更後
- /etc/httpd/conf/
- httpd.conf
- magic
- /etc/httpd/conf.d/
- autoindex.conf
- ssl.conf
- userdir.conf
- welcome.conf
- wsgi.conf
ssl.confは、cartbotのインストルが完了すると「/etc/httpd/conf.d」へ自動で作成されます。
①httpd.confのドキュメントルートとサーバネームをコメントアウトします。また、最下行に記述していたDjangoサイトの情報も削除します。
vi /etc/httpd/conf/httpd.conf
以下のようにコメントアウトします。
#DocumentRoot "/var/www/cgi-bin/test_django" 〜省略〜 #ServerName 独自に取得したドメイン名.com:80
以下のようにDjangoサイトの設定を削除します。
#以下すべて削除 LoadModule wsgi_module /home/username/test_django/lib/python3.6/site-packages/mod_wsgi/server/mod_wsgi-py36.cpython-36m-x86_64-linux-gnu.so WSGIPythonPath /var/www/cgi-bin/test_django WSGIScriptAlias /test_django /var/www/cgi-bin/test_django/test_django/wsgi.py <Directory /var/www/cgi-bin/test_django/test_django1> <Files wsgi.py> Require all granted </Files> </Directory> Alias /static/ /var/www/cgi-bin/test_django/static/ <Directory /var/www/cgi-bin/test_django/static/> Require all granted </Directory>
②新たに、wsgi.confを作成します。そこに、Djangoサイトの設定を記述します。
vi /etc/httpd/conf/wsgi.conf
以下のように編集します。
NmeVirtualHost *:80 LoadModule wsgi_module /home/username/test_django/lib/python3.6/site-packages/mod_wsgi/server/mod_wsgi-py36.cpython-36m-x86_64-linux-gnu.so WSGIPythonPath /var/www/cgi-bin/test_django WSGIScriptAlias / /var/www/cgi-bin/test_django/test_django/wsgi.py <VirtualHost *:80> DocumentRoot /var/www/cgi-bin/test_django ServerName www.独自に取得したドメイン名.com ServerAlias 独自に取得したドメイン名.com <Directory /var/www/cgi-bin/test_django> <Files wsgi.py> Require all granted </Files> </Directory> </VirtualHost> Alias /static/ /var/www/cgi-bin/test_django/static/ <Directory /var/www/cgi-bin/test_django/static/> Require all granted </Directory>
③Apache設定ファイルの文法が正しいか確認します。
apachectl configtest
④Apacheを再起動します。
systemctl restart httpd
⑤前回まで作ったページが開けるか確認します。以下のURLでアクセスします。
http://VPSのグローバルIPアドレス
OR
http://VPSに設定した独自ドメイン.com/
以下のように、ページが表示できれば成功です。
settings.pyの設定
「.well-known」ディレクトリを作成し、Djangoの設定ファイルにパスを記述します。「.well-known」は、Djangoに設定する証明書までの静的パスの場所になります。
①settings.pyに以下の内容を追記します。以下の設定では、プロジェクトディレクトリ(ここではtest_django)の直下の「.well-known」が置き場所となります。(パスは、好きな場所に変更してください。)
CERT_ROOT = os.path.join(BASE_DIR, '.well-known') CERT_URL = '/.well-known/'
②新しく指定するディレクトリの場合は実際にWebサーバ内に上記のディレクトリ(空でOK)を作成することも忘れないようにしてください。
cd /var/www/test_django/test_django mkdir .well-known cd .well-known mkdir acme-challenge
③テスト用の静的ファイルを作成します。
vi acme-challenge/test.html
以下のようなダミーな内容を記述します。
<!DOCTYPE html> <html> <head> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title></title> <meta charset="utf-8"> <meta name="description" content=""> <meta name="author" content=""> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href=""> <!--[if lt IE 9]> <script src="//cdn.jsdelivr.net/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="//cdnjs.cloudflare.com/ajax/libs/respond.js/1.4.2/respond.min.js"></script> <![endif]--> <link rel="shortcut icon" href=""> </head> <body> <!-- Place your content here --> <!-- SCRIPTS --> <!-- Example: <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> --> </body> </html>
certbotで証明書を作成するとき、well-knownディレクトリに静的ファイルがないと権限エラーになる場合があります。これを回避するため「test.html」を作りました。もしかすると必要ない?かもしれません。
Djangoプロジェクトは、以下のような構成になります。
- /var/www/..省略../test_django/
- db.sqlite3
- manage.py
- .well-known/
- acme-challenge/
- test.html
- static/
- test_django/
- settings.py
- polls/
④.well-knownディレクトリの所有者をrootから「webadmin01」へ変更します。
cd ../ sudo chown -R webadmin01:webadmin01 .well-known
Djangoプロジェクト内urls.pyの設定
①test_django/urls.pyに以下の設定を追記します。
from django.conf.urls.static import static from django.conf import settings 〜省略〜 urlpatterns += static(settings.CERT_URL, document_root=settings.CERT_ROOT)
Apacheの設定ファイルssl.confにバーチャルホストの設定
①ssl.confにバーチャルホストの設定をします。
suod vi /etc/httpd/conf.d/ssl.conf
以下のような設定を最終行に追加します。
Alias /.well-known/acme-challenge/ /var/www/cgi-bin/pj1/.well-known/acme-challenge/ <location .well-known=""> Options -Indexes </location>
.well-knownはDjangoの証明書ファイルの場所です。
httpsサービス・443ポートの開放
①httpsポートへのアクセス許可を行います。
firewall-cmd --add-port=443/tcp --zone=public firewall-cmd --add-port=443/tcp --zone=public --permanent
–permanentがないと一時的な設定でしかないのに注意して下さい。
②firewallのサービスの中にhttpsが用意されているので、サービスの登録を行います。
firewall-cmd --add-service=https --zone=public --permanent firewall-cmd --reload
以下のように登録できたか確認します。
sudo firewall-cmd --list-all public (active) target: default icmp-block-inversion: no interfaces: eth0 eth1 sources: services: ssh dhcpv6-client http mysql https ports: 443/tcp protocols: masquerade: no forward-ports: source-ports: icmp-blocks: rich rules:
SSL/TLS証明書の作成
①Apacheを再起動します。
systemctl restart httpd
②以下のコマンドで証明書を発行します。
certbot certonly --webroot -w /var/www/cgi-bin/test_django/.well-known/ -d hoge.com --email=xxx@xxx.xx
certonly | SSL/TLS サーバ証明書の取得のみを行います。証明書のインストール(サーバソフトウェアの設定)は行われません。 |
---|---|
–webroot | Webrootプラグインを使用する |
-w | ssl.confにも指定した証明書までの静的パスの場所 |
-w | ssl.confにも指定した証明書までの静的パスの場所 |
-d | ドメイン |
–email= | 証明書の有効期限を知らせるためのメールアドレス |
証明書の発行が成功すると以下のような結果が出力されます。
IMPORTANT NOTES: - Congratulations! Your certificate and chain have been saved at: /etc/letsencrypt/live/独自ドメイン名.com/fullchain.pem Your key file has been saved at: /etc/letsencrypt/live/独自ドメイン名.com/privkey.pem Your cert will expire on 2018-06-04. To obtain a new or tweaked version of this certificate in the future, simply run certbot again. To non-interactively renew *all* of your certificates, run "certbot renew" - If you like Certbot, please consider supporting our work by: Donating to ISRG / Let's Encrypt: https://letsencrypt.org/donate Donating to EFF: https://eff.org/donate-le
③発行できたか確認します。
ls -la /etc/letsencrypt/live/独自ドメイン名.com/ cert.pem -> ../../archive/独自ドメイン名.com/cert1.pem chain.pem -> ../../archive/独自ドメイン名.com/chain1.pem fullchain.pem -> ../../archive/独自ドメイン名.com/fullchain1.pem privkey.pem -> ../../archive/独自ドメイン名.com/privkey1.pem
次回
次回は、証明書の発行が完了したのでApacheの設定ファイルに設定します。
- Python 114
- 制作 54
- RaspberryPi 41
- Django 40
- WordPress 40
- Linux 27
- VPS 22
- JavaScript 21
- PHP 20
- HTML・CSS 19
- AWS 16
- 仮想環境 15
- レスポンシブデザイン 13
- マイコン 11
- WEB全般 11
- 動画製作 9
- Webサービス 8
- 統合開発環境 8
- 機械学習 8
- PyCharm 7
- jQuery 7
- AfterEffects 7
- 起業・設立 7
- Django REST framework 6
- C# 6
- デザイン 6
- SEO 6
- pydata 6
- Visual Studio 5
- 数学 5
- 携帯サイト 5
- heroku 5
- Mac 5
- illustrator 5
- node.js 5
- Anaconda 5
- Nginx 4
- Jupyter Notebook 4
- インフラ 4
- Google Colaboratory 4
- symfony 4
- Webスクレイピング 3
- photoshop 3
- Go言語 3
- PC 3
- ツール 3
- Docker 3
- facebook 3
- 作業効率化 3
- データベース 3
- Cloud9 3
- コマンド 2
- micro:bit 2
- Kali Linux 2
- Webサーバー 2
- MariaDB 2
- ドローン 2
- コンテナ 2
- DaVinci Resolve 2
- ネットワーク 2
- Java 2
- movie 2
- PCDJ 2
- 音楽 2
- XSERVER 2
- Ansible 1
- Vue.js 1
- JSON 1
- Bootstrap 1
- バージョン管理システム 1
- SSL 1
- S3 1
- ムームードメイン 1
- ネットワーク 1
- アニメーション 1
- D3.js 1
- Rhino 1
- アニメ 1
- git 1
- windows 1
- アクセス解析 1
- スマートフォン 1
- アフィリエイトノウハウ 1
- 知識 1
- TypeScript 1
- 役立つ本・書籍 1
- データサイエンス 1
- ESP32 1
- AI 1
- ownCloud 1
- API 1