[TIL] Nginx HTTPS 설정

김민재·2024년 9월 28일
0

TIL

목록 보기
165/172
post-thumbnail

HTTPS 설정으로 보안 강화

  • ec2로 배포 중인 서버에 HTTPS를 설정하려고 한다.
  • 도메인을 구입한 후 사용해야한다.
  1. ssh 서버에 접속한다.

  2. Cerbot 설치

    • sudo apt update
    • sudo apt install certbot
  3. Nginx 설치

    • sudo apt install python3-certbot-nginx

    3-1. Nginx 실행
    - sudo systemctl start nginx
    - sudo systemctl restart nginx
    - sudo systemctl stop nginx
    - sudo systemctl enable nginx

  4. SSL 인증서 발급

    • sudo certbot --nginx -d 도메인 -d www.도메인
  5. Nginx 설정 파일을 만들고 작성해준다.

  • sudo nano /etc/nginx/sites-available/default

  • nano nginx.conf

  • sudo nano /etc/nginx/sites-enabled/default

    server {
     listen 80;
     server_name xn--9r2b17b.shop www.xn--9r2b17b.shop;
    
     location / {
         return 301 https://$host$request_uri;  # HTTP 요청을 HTTPS로 리다이렉트
     }
    }
    
    server {
     listen 443 ssl;
     server_name xn--9r2b17b.shop www.xn--9r2b17b.shop;
    
     ssl_certificate /etc/letsencrypt/live/xn--9r2b17b.shop/fullchain.pem;
     ssl_certificate_key /etc/letsencrypt/live/xn--9r2b17b.shop/privkey.pem;
    
     location / {
         proxy_pass http://localhost:3000;  # Nest.js가 로컬에서 실행 중인 포트 - 도커를 이용하면 도커 컴포즈 네임
         proxy_http_version 1.1;
         proxy_set_header Upgrade $http_upgrade;
         proxy_set_header Connection 'upgrade';
         proxy_set_header Host $host;
         proxy_cache_bypass $http_upgrade;

// cors는 main.ts에서 설정했으면 nginx에서느 안해도된다.

    # CORS 헤더 추가
    add_header 'Access-Control-Allow-Origin' 'https://main--kimminjae98.netlify.app';
    add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
    add_header 'Access-Control-Allow-Headers' 'Content-Type, Authorization';

    # Preflight 요청 처리
    if ($request_method = OPTIONS) {
        add_header 'Access-Control-Allow-Origin' 'https://main--kimminjae98.netlify.app';
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
        add_header 'Access-Control-Allow-Headers' 'Content-Type, Authorization';
        add_header 'Content-Length' 0;
        return 204;
    }
}

}

  1. sudo nano /etc/hosts 명령어를 실행하여 도커 컨테이너 이름을 적어준다. 이렇게 해야지 nginx 컨테이너를 찾을 수 있음
  1. 이제 가비아 도메인으로 가면 https가 적용되었다.
profile
개발 경험치 쌓는 곳

0개의 댓글

관련 채용 정보