(Django) Let's Encrypt 사용하여 HTTP를 HTTPS 인증으로 변경하기
Django HTTPS 인증으로 변경하기
AWS로 배포한 웹 사이트를 HTTPS 로 변경하기 위해서 Let’s Encrypt 를 사용하여 무료 로 인증서를 발급받아 사용하였다. certbot을 설치하여 nginx에서 인증서를 획득하고 설치하는 과정을 진행할 예정이다
HTTP와 HTTPS란 ?
Let’s Encrypt란
Let’s Encrypt는 인증서를 발급해주는 인증 서비스 기관(CA)이다. 해당 기관은 SSL 인증서를 무료로 제공한다.
진행 과정
certbot을 설치
로컬과 ec2 서버중에서 ec2에서만 설치하고 등록해주면 된다. certbot의 nginx 패키지도 설치해준다
$ sudo add-apt-repository ppa:certbot/certbot
$ sudo apt install python-certbot-nginx
nginx 설정
nginx의 설정파일에 dns를 추가해주는데 이때 http로 접속했을때도 https로 리다이렉트 될 수 있게 설정해주었다.
server_name “자신의 사이트 dns” 나는 도메인을 가비아에서 만들어 53를 통해 연동시켜놓았다. https의 포트 번호는 443으로 http와 다르기 때문에 aws에서는 인바인드 규칙에 443포트를 0.0.0.0/0으로 열어놓아야 한다
이때 나는 nginx를 프로젝트에 .config 폴더에서 작성한 후 서버에 cp, ln이라는 명령어를 통해 서버에 복사하여 붙여넣는 방식으로 진행하기 때문에 프로젝트 파일 내에 있는 nginx 파일인 mysite.conf에 작성하였다.
nginx 설정 전에 nginx에 등록해야 하는 공개키와 개인키를 가져왔다. 아래 코드에서 IMPORTANT NOTES:의 중간쯤에 키들의 path가 나오는데 해당 path들을 복사하여 nginx파일에 붙여넣어 준다
ubuntu@ip-172-31-5-89:/srv/Neo-News/.config/nginx$ sudo certbot --nginx -d neonews.site # 해당 dns에 대한 개인키, 공개키 생성해준다
Saving debug log to /var/log/letsencrypt/letsencrypt.log
Plugins selected: Authenticator nginx, Installer nginx
Cert not yet due for renewal
You have an existing certificate that has exactly the same domains or certificate name you requested and isn't close to expiry.
(ref: /etc/letsencrypt/renewal/neonews.site.conf)
What would you like to do?
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
1: Attempt to reinstall this existing certificate
2: Renew & replace the cert (limit ~5 per 7 days)
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Select the appropriate number [1-2] then [enter] (press 'c' to cancel): 1 # 번호 선택해야 한다
Keeping the existing certificate
Deploying Certificate to VirtualHost /etc/nginx/sites-enabled/mysite.conf
Please choose whether or not to redirect HTTP traffic to HTTPS, removing HTTP access.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
1: No redirect - Make no further changes to the webserver configuration.
2: Redirect - Make all requests redirect to secure HTTPS access. Choose this for
new sites, or if you're confident your site works on HTTPS. You can undo this
change by editing your web server's configuration.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Select the appropriate number [1-2] then [enter] (press 'c' to cancel): 2 # 번호 선택해야 한다
No matching insecure server blocks listening on port 80 found.
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Congratulations! You have successfully enabled https://neonews.site
You should test your configuration at:
https://www.ssllabs.com/ssltest/analyze.html?d=neonews.site
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
IMPORTANT NOTES:
- Congratulations! Your certificate and chain have been saved at:
/etc/letsencrypt/live/neonews.site/fullchain.pem # 생성된 공개키 path
Your key file has been saved at:
/etc/letsencrypt/live/neonews.site/privkey.pem # 생성된 개인키 path
Your cert will expire on 2021-11-14. To obtain a new or tweaked
version of this certificate in the future, simply run certbot again
with the "certonly" option. 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
/etc/letsencrypt/live/neonews.site/fullchain.pem # 생성된 공개키 path
/etc/letsencrypt/live/neonews.site/privkey.pem # 생성된 개인키 path
가져온 인증서는 90일 동안만 유효하다고 한다. 이때 Certbot 패키지를 설치하여 이를 자동으로 갱신해줄 수 있다
$ sudo certbot renew --dry-run
위에서 가져온 개인키 공개키의 path를 https 443 server안에 붙여 넣어주었다. 이후에는 http였을때 작성해놓았던 static같은 내용을 전부 https로 옮겨주었다.
server {
listen 80;
server_name neonews.site;
charset utf-8;
return 301 https://$host$request_uri;
}
server {
listen 443 ssl;
server_name neonews.site;
ssl_certificate /etc/letsencrypt/live/neonews.site/fullchain.pem; # 공개키
ssl_certificate_key /etc/letsencrypt/live/neonews.site/privkey.pem; # 개인키
charset utf-8;
client_max_body_size 128M;
location / {
uwsgi_pass unix:///tmp/mysite.sock;
include uwsgi_params;
}
location /static/ {
alias /srv/Neo-News/static/;
}
}
이후 서버에서 pull 받은뒤 nginx를 서버에 적용시켜주기 위해서 아래와 같은 명령어를 입력하였다. 서버 자체에 만든 사람은 서버로 가서 sites-available과 sites-enabled에 적용시켜주면 된다.
ubuntu@ip-172-31-5-89:/srv/Neo-News$ sudo cp -f /srv/Neo-News/.config/nginx/mysite.conf /etc/nginx/sites-available/mysite.conf # 프로젝트에 있는 nginx 내용 available에 복사
ubuntu@ip-172-31-5-89:/srv/Neo-News$ sudo ln -sf /etc/nginx/sites-available/mysite.conf /etc/nginx/sites-enabled/mysite.conf # 서버에 존재하는 sites-enabled에도 똑같이 적용
ubuntu@ip-172-31-5-89:/srv/Neo-News$ sudo systemctl daemon-reload && sudo systemctl # 변경후 reload를 잊지말자
이후 자신의 사이트에 들어가면 https가 적용되어 있는 것을 볼 수 있다 ! http로 들어가도 https로 리다이렉트 되는 것을 볼 수 있다
주의 할 점
진행중에 위와 같이 진행해도 http에서 https로 리다이렉트 되지 않고 계속 에러가 발생하는 문제를 겪었는데.. 로직이 잘못된 것이 아니라 기존에 캐시값이 존재해서 그런것이다.. 이 사실을 몰라서 1-2시간을 계속해서 로직을 변경하고 찾아보았다.. 구글 세팅즈에 있는 Clear browsing data 를 지워주면 깔끔하게 적용된다 !
reference
https://daily-life-of-bsh.tistory.com/225
https://twpower.github.io/44-set-free-https-by-using-letsencrypt
https://blog.crois.net/2019/02/06/centos7-lets-encrypt-%EC%84%A4%EC%A0%95-%EB%B0%8F-apache-nginx-%EC%84%A4%EC%A0%95/