https, http2

김무연·2023년 12월 13일

Backend

목록 보기
29/49

https

웹 서버에 SSL 암호화를 추가하는 모듈

  • 오고 가는 데이터를 암호화해서 중간에 다른 사람이 요청을 가로채더라도 내용을 확인할 수 없음
  • 요즘에는 HTTPS 적용이 필수(개인 정보가 있는 곳은 특히!)
  • 주소 왼쪽에 자물쇠 아이콘이 나타남

https 서버

http 서버를 https 서버로 변경

  • 암호화를 위해 인증서가 필요한데 발급받아야 함
  • http모듈과 https 모듈은 다름

createServer가 인자를 두개를 받음

  • http 서버와는 달리 createServer할 때 인자를 한 개 더 받음
  • 첫 번째 인자는 인증서와 관련된 옵션 객체
  • pem, crt, key 등 인증서를 구입할 때 얻을 수 있는 파일 넣기
  • 두 번째 인자는 서버 로직
  • 인증서를 넣지 않고 서버를 실행하게 되면 자물쇠는 뜨지만 인증서를 넣으라고 경고창이 뜸
  • https 인 경우에는 포트번호 443
  • 무료 SSL/TLS 인증서를 발급받기 위한 사이트 Let's Encrypt
    https://letsencrypt.org/ko/

https서버 만들기

const https = require('https');
const fs = require('fs');

https.createServer({
  cert: fs.readFileSync('도메인 인증서 경로'),
  key: fs.readFileSync('도메인 비밀키 경로'),
  ca: [
    fs.readFileSync('상위 인증서 경로'),
    fs.readFileSync('상위 인증서 경로'),
  ],
}, (req, res) => {
  res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
  res.write('<h1>Hello Node!</h1>');
  res.end('<p>Hello Server!</p>');
})
  .listen(443, () => {
    console.log('443번 포트에서 서버 대기 중입니다!');
  });

http2

SSL 암호화와 더불어 최신 HTTP 프로토콜인 http2를 사용하는 모듈

  • 요청 및 응답 방식이 기존 http/1.1보다 개선됨
  • 웹의 속도도 개선됨

http2 서버 만들기

https 모듈을 http2로, createServer 메서드를 createSecureServer 메서드로 변경

const http2 = require('http2');
const fs = require('fs');

http2.createSecureServer({
  cert: fs.readFileSync('도메인 인증서 경로'),
  key: fs.readFileSync('도메인 비밀키 경로'),
  ca: [
    fs.readFileSync('상위 인증서 경로'),
    fs.readFileSync('상위 인증서 경로'),
  ],
}, (req, res) => {
  res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
  res.write('<h1>Hello Node!</h1>');
  res.end('<p>Hello Server!</p>');
})
  .listen(443, () => {
    console.log('443번 포트에서 서버 대기 중입니다!');
  });
profile
Notion에 정리된 공부한 글을 옮겨오는 중입니다... (진행중)

0개의 댓글