[Nginx] HTTPS 설정하기

Asher Kim·2021년 8월 25일
0
post-thumbnail

nginx 설치하기 - 바로가기

2. Nginx HTTPS 설정하기

sudo vi /etc/nginx/sites-available/default

// 전체 주석 또는 전체 삭제 후 아래와 같이 입력

server {
        listen 443 ssl;

        server_name example.com www.example.com;
        ssl_certificate         파일경로/pem파일명.ca-bundle.pem;
        ssl_certificate_key     파일경로/key파일명.key;
        ssl_prefer_server_ciphers on;

	// 필자는 Next.js 를 이용하여 location이 html이 아님 root또한 없음
        location / {
                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_cache_bypass $http_upgrade;
        }
}

설정 후 
sudo systemctl restart nginx로 서비스 재실행

** key 파일 경우에는 비밀번호가 걸려있어 permission 에러가 발생하는데 필자는 잠긴 key파일을 오픈해주었다.
openssl rsa -in 파일명.key -out 파일명.key 
입력 후 비밀번호 입력하면 비밀번호가 삭제된다

이렇게 하면 https 로 접근이 가능하다. 하지만 https 만 설정해주었기 때문에 http로 접속 시에는 없는 도메인으로 인식을 하기 때문에 http to https 소스를 추가해서 http로 접속해도 https로 접속이 가능하게 설정이 필요하다

server {
        listen 80;
        server_name example.com www.example.com;

        location / {
        return 301 https://www.example.com$request_uri;
    }
}

너무 간단하다

이제 http, https 둘다 접속이 가능하다.

설정 이후

sudo systemctl restart nginx
는 필수 !

전체코드

파일열기 > sudo vi /etc/nginx/sites-available/default

server {
        listen 80;
        server_name ashpor.com www.ashpor.com;

        location / {
        return 301 https://www.ashpor.com$request_uri;
    }
}

server {
        listen 443 ssl;

        server_name ashpor.com www.ashpor.com;
        ssl_certificate         private/www.ashpor.com_202108251S42.ca-bundle.pem;
        ssl_certificate_key     private/www.ashpor.com.key;
        ssl_prefer_server_ciphers on;

        location / {
                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_cache_bypass $http_upgrade;
        }
}

nginx.conf 파일은 변경된 사항 없음 !

profile
공부 기록 일지 작성하기 프로젝트 🤪

0개의 댓글