배포, 운영/Infra

[Infra] HTTPS 적용

Ash_jisu 2024. 12. 16. 10:21

HTTPS 적용 개요

HTTPS 사용 이유

  • HTTPS는 데이터를 암호화하여 클라이언트와 서버 간 통신을 안전하게 만듬
  • 개인정보 보호 및 데이터 무결성을 유지하며, 브라우저에서 "보안되지 않은 연결" 경고를 방지
  • Let's Encrypt를 활용하면 무료로 SSL/TLS 인증서를 발급받아 HTTPS를 구현

Webroot 방식으로 HTTPS 적용

Certbot 대신 Webroot 방식을 사용하는 이유

  • Amazon Linux 2에서는 python3-certbot-nginx 패키지가 지원되지 않아 Certbot을 통한 자동 설정이 어렵다
  • 대신 Webroot 방식을 사용해 Nginx를 통한 HTTPS를 설정한다

Webroot를 활용한 인증서 발급

1. 인증서 발급

  • /home/ec2-user/dist는 example로 정적 index.html파일이 들어있는 폴더로 지정해주면 된다
sudo certbot certonly --webroot -w /home/ec2-user/dist -d yourdomain.com -d www.yourdomain.com+

2. 발급 성공 메시지 확인

  • 아래 명령어로 발급된 인증서 확인 가능
sudo ls -l /etc/letsencrypt/live/yourdomain.com/

 

 

Nginx 설정 업데이트

1. Nginx 설정 파일 수정 명령어

sudo nano /etc/nginx/conf.d/spring-app.conf

 

2. HTTPS 설정 추가

server {
    listen 443 ssl;
    server_name yourdomain.com www.yourdomain.com;

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

    # 정적 파일 제공
    location / {
        root /home/ec2-user/dist;
        index index.html;
        try_files $uri $uri/ /index.html;
    }

    # API 요청 프록시
    location /api/ {
        proxy_pass http://localhost:8080;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
}

server {
    listen 80;
    server_name yourdomain.com www.yourdomain.com;
    return 301 https://$host$request_uri;
}

3. Nginx 재시작

sudo systemctl restart nginx

 

적용완료

 

 


인증서 갱신(수동, 자동)

수동 갱신

  • 수동 갱신 및 Nginx 재실행
sudo certbot renew --dry-run

sudo systemctl reload nginx
  • 성공 메세지

자동 갱신

1. Crontab 설정

sudo systemctl start crond
sudo systemctl enable crond
sudo crontab -e

 

2. Crontab에 자동 갱신 작업 추가(30일 마다)

0 0 */30 * * certbot renew --quiet --deploy-hook "systemctl reload nginx"

 

3. 설정 확인

sudo crontab -l

 


로그인 세션 관련 문제 해결

문제 발생

  • HTTPS 적용 후, 세션 인증을 사용하는 프로젝트에서 CORS 에러 발생

해결 방법

  • Spring Boot에서 CORS 설정 추가
public void addCorsMappings(CorsRegistry registry) {
    registry.addMapping("/**")
            .allowedOrigins("https://yourdomain.com", "https://www.yourdomain.com")
            .allowedMethods("GET", "POST", "PATCH", "DELETE", "PUT")
            .allowedHeaders("*")
            .allowCredentials(true); // 인증 정보(쿠키 등) 허용
}