tech.junha.kr

[Ubuntu] NGINX 설치 + Let's Encrypt 설치

1. NGINX as a Reverse Proxy

root권한으로 application을 실행하는 건 권장하지 않는다.

NGNIX를 이용해 프록시 서버를 두자.

# default로 설치 된 apache2 제거

sudo apt remove apache2
sudo apt purge apache2
sudo apt install nginx
# 포트 허용
sudo ufw allow ssh
sudo ufw allow http
sudo ufw allow https

# 방화벽 활성화
sudo ufw enable
sudo ufw status

2. NGINX 설정 파일 변경

sudo vi /etc/nginx/nginx.conf
user www-data;
worker_processes auto;
pid /run/nginx.pid;
include /etc/nginx/modules-enabled/*.conf;

events {
    worker_connections 768;
}

http {

    sendfile on;
    tcp_nopush on;
    types_hash_max_size 2048;

    include /etc/nginx/mime.types;
    default_type application/octet-stream;

    ssl_protocols TLSv1 TLSv1.1 TLSv1.2 TLSv1.3;
    ssl_prefer_server_ciphers on;

    access_log /var/log/nginx/access.log;
    error_log /var/log/nginx/error.log;

    gzip on;

    include /etc/nginx/conf.d/*.conf;
    include /etc/nginx/sites-enabled/*;
}
sudo vi /etc/nginx/sites-available/default
server {
    listen 80 default_server;
    listen [::]:80 default_server;

    root /var/www/html;

    index index.html index.htm index.nginx-debian.html;

    server_name _;

    location / {
	    # 포트 포워딩 설정
        proxy_pass http://localhost:3001;
        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;
    }
}
sudo systemctl restart nginx

Nginx 코드

# 설정 파일을 검사하여 구문 오류가 있는지 확인
sudo nginx -t
# nginx의 error.log 파일을 실시간으로 모니터링
tail -f /var/log/nginx/error.log

3. LetsEncrypt 적용

sudo apt-get install certbot python3-certbot-nginx
sudo certbot --nginx -d example.com -d www.example.com

# 90일 밖에 안되니 자동 재생성 코드
sudo certbot renew

https로 리다이렉트 코드블럭 교체

server {
    listen 80;
    listen [::]:80;
    server_name wiseprint.cloud www.wiseprint.cloud;
    return 301 https://$host$request_uri;
}