0. Connecting to an Instance
AWS CLI를 사용하여 인스턴스의 Linux OS 플랫폼 및 버전 정보 확인
uname
cat /proc/version
Linux version ~ ... ~ (Red Hat 11.4.1-2), ~ ...
Redhat 계열(centOS) - yum
Debian, Ubuntu - apt-get
1. Installing Nginx
nginx directory 생성
Nginx: 정적 컨텐츠를 제공해주는 프록시 서버
sudo yum install nginx
cd /etc && ls | grep nginx // check settings
sudo mkdir /etc/nginx/sites-available
sudo mkdir /etc/nginx/sites-enabled
2. Setting up config
1) nginx.conf 수정
: nginx 관련 설정을 블록 단위로 설정, sites-enable에 존재하는 파일 불러옴
sudo vi /etc/nginx/nginx.conf
include /etc/nginx/sites-enabled/*.conf;
# server {
# listen 80;
# listen [::]:80;
# server_name _;
# root /usr/share/nginx/html;
#
# # Load configuration files for the default server block.
# include /etc/nginx/default.d/*.conf;
#
# error_page 404 /404.html;
# location = /404.html {
# }
#
# error_page 500 502 503 504 /50x.html;
# location = /50x.html {
# }
# }
2) server 설정
: nginx 최신 버전을 따로 설치하지 않고 기본 설정된 repository에 있는 버전을 install nginx로 바로 설치한 경우에는 nginx 환경 설정 파일 위치가 /etc/nginx/sites-available/default로 설정됨,
최신 버전을 설치했을 경우 /etc/nginx/conf.d/default.conf [5]
sudo vi /etc/nginx/sites-available/default.conf
server {
listen 80;
location / {
root /project/nginx-project; // path to deploy
index index.html index.htm;
try-files $url $url/ /index.html;
}
}
3) symbolic link 설정
: sites-enabled directory에 default.conf 바로가기 생성
sites-available에 존재하는 설정 파일들 중, 사용하는 설정 파일만 link해서 사용할 수 있도록 하는 디렉터리
cd /etc/nginx/sites-enabled
sudo ln -s /etc/nginx/sites-available/default.conf
ls -l
total 0
lrwxrwxrwx. 1 root root 39 Jul 30 04:42 default.conf → /etc/nginx/sites-available/default.conf
4) 웹서버 html 설정
sudo vi /project/nginx-project/index.html
<!DOCTYPE html>
<html>
<head>
<title>Welcome to Nginx!</title>
</head>
<body>
<h1>Welcome to Nginx!</h1>
<p>If you see this page, the Nginx web server is successfully installed and working.</p>
<p>Further configuration is required.</p>
</body>
</html>
3. Run the server
sudo systemctl start nginx
오류 시
status : Failed to start nginx.service - The nginx HTTP and reverse proxy server
sudo systemctl start nginx
Job for nginx.service failed because the control process exited with error code.
See "systemctl status nginx.service" and "journalctl -xeu nginx.service" for details.
: 80번 포트에 수신 대기중인 프로세스 삭제
fuser -k 80/tcp
4. Prepare SSL/TLS Certificate
- Generate a self-signed certificate or obtain a certificate from a Certificate Authority (CA)
1) Ensure that OpenSSL is installed on your operating system
openssl version
nginx가 ssl 적용이 가능한 모듈이 있는지 확인 (--with-http_ssl_module)
nginx -V
nginx version: nginx/1.24.0
built with OpenSSL 3.0.8 7 Feb 2023
TLS SNI support enabled
configure arguments: --prefix=/usr/share/nginx --sbin-path=/usr/sbin/nginx --modules-path=/usr/lib64/nginx/modules --conf-path=/etc/nginx/nginx.conf --error-log-path=/var/log/nginx/error.log --http-log-path=/var/log/nginx/access.log --http-client-body-temp-path=/var/lib/nginx/tmp/client_body --http-proxy-temp-path=/var/lib/nginx/tmp/proxy --http-fastcgi-temp-path=/var/lib/nginx/tmp/fastcgi --http-uwsgi-temp-path=/var/lib/nginx/tmp/uwsgi --http-scgi-temp-path=/var/lib/nginx/tmp/scgi --pid-path=/run/nginx.pid --lock-path=/run/lock/subsys/nginx --user=nginx --group=nginx --with-compat --with-debug --with-file-aio --with-google_perftools_module --with-http_addition_module --with-http_auth_request_module --with-http_dav_module --with-http_degradation_module --with-http_flv_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_image_filter_module=dynamic --with-http_mp4_module --with-http_perl_module=dynamic --with-http_random_index_module --with-http_realip_module --with-http_secure_link_module --with-http_slice_module --with-http_ssl_module --with-http_stub_status_module --with-http_sub_module --with-http_v2_module --with-http_xslt_module=dynamic --with-mail=dynamic --with-mail_ssl_module --with-openssl-opt=enable-ktls --with-pcre --with-pcre-jit --with-stream=dynamic --with-stream_realip_module --with-stream_ssl_module --with-stream_ssl_preread_module --with-threads --with-cc-opt='-O2 -ftree-vectorize -flto=auto -ffat-lto-objects -fexceptions -g -grecord-gcc-switches -pipe -Wall -Werror=format-security -Wp,-D_FORTIFY_SOURCE=2 -Wp,-D_GLIBCXX_ASSERTIONS -specs=/usr/lib/rpm/redhat/redhat-hardened-cc1 -fstack-protector-strong -specs=/usr/lib/rpm/redhat/redhat-annobin-cc1 -m64 -march=x86-64-v2 -mtune=generic -fasynchronous-unwind-tables -fstack-clash-protection -fcf-protection' —with-ld-opt='-Wl,-z,relro -Wl,—as-needed -Wl,-z,now -specs=/usr/lib/rpm/redhat/redhat-hardened-ld -specs=/usr/lib/rpm/redhat/redhat-annobin-cc1 -Wl,—build-id=sha1 -Wl,-dT,/builddir/build/BUILD/nginx-1.24.0/.package_note-nginx-1.24.0-1.amzn2023.0.2.x86_64.ld -Wl,-E’
2) 인증서 작업할 폴더 생성 (/usr/local/ssl)
3) Generate the Private Key
- Use the following OpenSSL command to generate the private key:
openssl genrsa -des3 -out server.key 2048
Enter PEM pass phrase:
> server.key 생성
4) Create a Certificate Signing Request (CSR)
- Use the following OpenSSL command to generate the certificate signing request (CSR) file:
openssl req -new -key server.key -out server.csr
- During this process, you will be prompted to enter information such as country, state, city, company name, and domain name
5) Generate the Self-Signed Certificate
- Use the following OpenSSL command to generate the self-signed certificate:
openssl x509 -req -days 3650 -in server.csr -signkey server.key -out server.crt
- -days 3650: 3650일짜리(10년) 인증서
- -in server.csr -signkey server.key: 개인 키와 서버 요청서를 가지고 인증서 server.crt 생성
5. Configure the Nginx configuration file
- Add the following HTTPS-related settings inside the server block:
- Use the listen directive to specify port 443
- Use the ssl_certificate and ssl_certificate_key directives to specify the paths to the certificate files
> cd /etc/nginx/conf.d/
> sudo cp www.example.com.conf www.example.com.conf.bak
> sudo mkdir /etc/nginx/ssl
> sudo chmod 700 /etc/nginx/ssl
> sudo nano www.example.com.conf
server {
listen 443 ssl;
server_name www.example.com;
ssl_certificate /usr/local/ssl/server.crt;
ssl_certificate_key /usr/local/ssl/server.key;
## omitted below
}
+ 공인 인증기관에서 발급하지 않은 인증서는 윈도우에서 host 파일을 수정하여 접근할 것
(참고)
vi /etc/nginx/conf.d/default.conf
vi /etc/nginx/sites-available/default.conf
server {
listen 443 ssl;
server_name nginx-ssl-test.com;
ssl_certificate /usr/local/ssl/server.crt;
ssl_certificate_key /usr/local/ssl/server.key;
ssl_session_timeout 5m;
ssl_protocols SSLv2 SSLv3 TLSv1;
ssl_ciphers HIGH:!aNULL:!MD5;
ssl_prefer_server_ciphers on;
location / {
root /home/espeniel;
index index.html index.htm;
}
}
6. Set up HTTP to HTTPS redirection
- Configure the server block to redirect HTTP (port 80) requests to HTTPS
- Use the return 301 directive to achieve the redirection
vi /etc/nginx/sites-available/default.conf
server {
listen 80 default_server;
server_name nginx-ssl-test.com;
return 301 https://$host$request_uri;
}
- nginx 서비스 확인
ps -ef | grep nginx
systemctl restart nginx
오류 시
(1) /usr/local/ssl/server.key 파일의 권한과 소유자 확인
sudo chmod 644 server.key
sudo chown nginx:nginx server.key
(2) openssl rsa -check -in /usr/local/ssl/server.key
(3) 로그 확인
sudo journalctl -u nginx
Jul 30 08:59:35 ip-172-31-39-33.ec2.internal nginx[3006]: nginx: [emerg] cannot load certificate key "/usr/local/ssl/server.key": PEM_read_bio_PrivateKey() failed (SSL: error:1400006B:UI routines::processing error:while reading strings error:0480006D:PEM routin>
Jul 30 08:59:35 ip-172-31-39-33.ec2.internal nginx[3006]: nginx: configuration file /etc/nginx/nginx.conf test failed
→ The private key has a passphrase requirement but nginx is not configured to use a passphrase.
7. delete key passphrase
1) Rename the existing server.key filename to server_pass.key
mv server.key server_pass.key
2) Create a new key without a passphrase requirement. It is assumed that the RSA key in use, otherwise adjust the command accordingly. When prompted, type the passphrase and press enter
openssl rsa -in server_pass.key -out server.key
3) Stop, start nginx service and check that no error message are displayed
8. local test
- www.example.com은 공인된 도메인이 아니라 사내에서 사용할 가상 도메인이므로 클라이언트 측 도메인에 대한 hosts 파일을 등록해야 함
9. (optional) Additional SSL/TLS-related Settings
- Use the ssl_session_cache and ssl_session_timeout directives to configure the SSL session cache
- Use the ssl_prefer_server_ciphers direcactive to prefer the server's cipher suites
- Use the add_header directive to add security-related headers
10. Test Configuration and Restart Nginx
- Use the nginx -t command to check the syntax of the configuration file
- Use the systemctl restart nginx command to restart the Nginx service
sudo nginx -t
sudo nginx -s reload
References:
[1] [AWS] EC2 인스턴스에 Nginx 적용하기
[2] [AWS] EC2 NGINX 설치하고 Config설정 및 배포하기
[3] OpenSSL로 개인키 발급 및 SSL 인증서 생성#1
[4] Nginx https 적용하기 openssl 사용, http https로 리다이렉트
[5] Ubuntu에서 Nginx SSL 인증서 설정하는 방법
[6] DPSearch - Nginx service fails to start after installing new SSL certificate
'Networking > Network' 카테고리의 다른 글
[essentials#02] Telnet (0) | 2025.02.06 |
---|---|
[essentials#01] Server-Client communication using Netcat (0) | 2025.02.06 |
VPN - Site-to-Site, Client VPN (0) | 2024.02.13 |
보안 그룹과 네트워크 ACL(Stateful vs Stateless) (0) | 2024.02.12 |
UDP/TCP - 3-4단계 핸드셰이크 (1) | 2024.02.11 |