본문 바로가기

코딩

nginx 설치 및 설정

728x90
반응형

1. Nginx 설치

sudo apt update
sudo apt install nginx -y

2. Nginx 설정 파일 생성

 

sudo tee /etc/nginx/sites-available/django_app > /dev/null << 'EOF'
upstream django_app {
server unix:/run/gunicorn.sock fail_timeout=0;
}

server {
listen 80;
server_name your-domain.com www.your-domain.com;

# 클라이언트 최대 업로드 크기
client_max_body_size 100M;

# 보안 헤더
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-XSS-Protection "1; mode=block" always;
add_header Referrer-Policy "no-referrer-when-downgrade" always;
add_header Content-Security-Policy "default-src 'self' http: https: data: blob: 'unsafe-inline'" always;

# Gzip 압축
gzip on;
gzip_vary on;
gzip_min_length 1024;
gzip_proxied expired no-cache no-store private auth;
gzip_types
    text/plain
    text/css
    text/xml
    text/javascript
    application/x-javascript
    application/xml+rss
    application/javascript
    application/json;

# 정적 파일 서빙
location /static/ {
    alias /path/to/your/django/project/staticfiles/;
    expires 30d;
    add_header Cache-Control "public, immutable";
}

location /media/ {
    alias /path/to/your/django/project/media/;
    expires 30d;
    add_header Cache-Control "public, immutable";
}

# favicon.ico
location = /favicon.ico {
    log_not_found off;
    access_log off;
}

# robots.txt
location = /robots.txt {
    log_not_found off;
    access_log off;
}

# Django 애플리케이션
location / {
    proxy_pass http://django_app;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto $scheme;
    proxy_set_header Host $http_host;
    proxy_redirect off;
    proxy_buffering off;
}

# 에러 페이지
error_page 404 /404.html;
error_page 500 502 503 504 /50x.html;
location = /50x.html {
    root /usr/share/nginx/html;
}
}
EOF

3. 사이트 활성화

sudo ln -sf /etc/nginx/sites-available/django_app /etc/nginx/sites-enabled/
sudo rm -f /etc/nginx/sites-enabled/default

4. Nginx 설정 테스트

sudo nginx -t

5. Nginx 시작 및 활성화

sudo systemctl restart nginx
sudo systemctl enable nginx

6. 방화벽 설정 (UFW 사용 시)

sudo ufw allow 'Nginx Full'
sudo ufw allow ssh

7. 상태 확인

sudo systemctl status nginx

728x90
반응형