작성완료

Nginx로 SSL 인증서 적용
SSL 인증서를 Nginx에 적용하기 위해 필요한 인증서 파일과 개인키 파일을 준비하고, Ubuntu에 Nginx를 설치한 후 설정 파일을 수정하여 HTTP 요청을 HTTPS로 리다이렉트하며, WebSocket을 설정하는 방법을 설명합니다. 마지막으로 PM2를 사용해 서버를 실행하는 방법도 안내합니다.
1. 인증서 파일 준비
- 인증서 파일 : (예시)
private.key또는private.pem - 개인키 파일 : (예시)
cert.crt또는cert.pem - 체인(중간 체인) 파일 : (예시)
chain.crt
2. Ubuntu 또는 기타 운영체제에 Nginx 설치 및 설정 (예시는 Ubuntu)
2.1. 설치
apt update
apt install nginx -y
2.2. 설치 확인 및 재부팅시 자동 재실행 설정
systemctl status nginx
systemctl enable nginx
2.3. Nginx 설정 파일 오픈
vi /etc/nginx/sites-available/default
2.4. Nginx 설정
server {
listen 80;
server_name 나의도메인.com www.나의도메인.com;
# HTTP 요청을 HTTPS로 리다이렉트
return 301 https://$host$request_uri;
}
server {
listen 443 ssl;
server_name 나의도메인.com www.나의도메인.com;
# 인증서 파일
ssl_certificate /keys/cert.crt;
# 개인키 파일
ssl_certificate_key /keys/private.key;
# HTTP
location / {
proxy_pass http://localhost:3000;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
# WS (필요시 추가)
location /ws {
proxy_pass http://localhost:3000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "Upgrade";
proxy_set_header Host $host;
proxy_read_timeout 60s;
}
}
2.5. Nginx 설정 적용
systemctl reload nginx
3. 서버 설정 (예시는 NestJS)
import {
OnGatewayConnection,
WebSocketGateway,
WebSocketServer,
} from '@nestjs/websockets';
import { Server, WebSocket } from 'ws';
// 포트는 입력하지 않아야 한다. (HTTP 서버 포트 같이 사용)
@WebSocketGateway({ path: '/ws' })
export class WsService implements OnGatewayConnection {
@WebSocketServer()
protected server: Server;
public async handleConnection(client: WebSocket) {
client.send('웹소켓 새로운 연결');
}
}
Nginx에서
http://localhost:3000경로를 가르키고 있기 때문에 서버는3000포트로 켜야 한다.
4. 서버 실행 (예시는 PM2)
# NestJS인 경우
pm2 start main.js --name app
# NextJS인 경우
pm2 start npm --name app -- run start