nginx: 정적 사이트 + SSL + HTTP→HTTPS

정적 사이트(SSG) 배포 시 가장 흔한 nginx 구성 패턴

분야: DevOps/인프라 nginxsslhttpsletsencryptcertbot

정적 사이트를 nginx로 서빙할 때 자주 쓰는 구성입니다.

초보자 튜토리얼(처음부터 끝까지): nginx로 정적 웹사이트 + HTTPS 구축하기

예시 설정

server {
    server_name example.com;
    root /var/www/example.com/html;
    index index.html;

    # LetsEncrypt(ACME)
    location ^~ /.well-known/acme-challenge/ {
        root /var/www/letsencrypt;
    }

    # 민감 파일 차단(실수 방지)
    location ~ /\.(?!well-known) {
        return 404;
    }

    # (선택) 해시 기반 정적 자산 캐시 예시 (Astro: /_astro/)
    location ^~ /_astro/ {
        try_files $uri =404;
        expires 365d;
        add_header Cache-Control "public, max-age=31536000, immutable";
    }

    location / {
        try_files $uri $uri/ =404;
    }

    listen 443 ssl;
    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
}

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

원샷 명령줄 (정적 사이트 + HTTPS)

아래 스크립트는 Ubuntu 기준으로 “nginx 설치 → 사이트 설정 → certbot 발급/리다이렉트”까지 한 번에 진행합니다.

export DOMAIN="example.com"
export EMAIL="you@example.com"

sudo bash -euo pipefail <<BASH
set -euo pipefail

: "\${DOMAIN:?DOMAIN is required}"
: "\${EMAIL:?EMAIL is required}"

apt-get update -y
apt-get install -y nginx certbot python3-certbot-nginx

mkdir -p "/var/www/\${DOMAIN}/html"
mkdir -p /var/www/letsencrypt
echo "It works" >"/var/www/\${DOMAIN}/html/index.html"

cat >"/etc/nginx/sites-available/\${DOMAIN}" <<NGINX
server {
  listen 80;
  listen [::]:80;
  server_name \${DOMAIN};

  root /var/www/\${DOMAIN}/html;
  index index.html;

  location ^~ /.well-known/acme-challenge/ {
    root /var/www/letsencrypt;
  }

  location ~ /\\.(?!well-known) {
    return 404;
  }

  location / {
    try_files \\$uri \\$uri/ =404;
  }
}
NGINX

ln -sf "/etc/nginx/sites-available/\${DOMAIN}" "/etc/nginx/sites-enabled/\${DOMAIN}"
rm -f /etc/nginx/sites-enabled/default || true

nginx -t
systemctl reload nginx

certbot --nginx -d "\${DOMAIN}" --non-interactive --agree-tos -m "\${EMAIL}" --redirect
certbot renew --dry-run
BASH

체크리스트

  • /_astro/ 같은 해시 자산은 immutable 캐시 적용
  • /.well-known/acme-challenge/ 경로는 certbot용으로 열어두기
  • HTTP는 301로 HTTPS로 리다이렉트

같은 분야의 템플릿