Server

[Server] Nginx 리버스 프록시(Reverse Proxy) 개념 및 구축

테런 2024. 6. 12. 15:12
Overview
리버스 프록시(Reverse Proxy)는 일반적인 프록시 서버와는 반대로 클라이언트와 서버 간의 통신을 중계하는 서버입니다. 클라이언트가 서버에 요청을 보내면 리버스 프록시는 해당 요청을 받아서 이를 대신하여 원격 서버에 전달하고, 서버로부터의 응답을 클라이언트에게 전달합니다.

* 리버스 프록시의 주요 기능은 다음과 같습니다.
1. 보안 강화: 리버스 프록시를 사용하면 클라이언트와 서버 간의 직접적인 통신을 차단하고, 중간에서 요청을 중계함으로써 보안을 강화할 수 있습니다. 클라이언트는 리버스 프록시만을 볼 수 있고, 서버는 리버스 프록시만을 클라이언트로 인식합니다.

2. 로드 밸런싱: 리버스 프록시는 여러 대의 서버에 요청을 분산시킬 수 있어서 로드 밸런싱을 구현할 수 있습니다. 이를 통해 트래픽이 고르게 분산되어 서버의 성능과 가용성을 향상시킬 수 있습니다.

3. 캐싱: 리버스 프록시는 요청에 대한 응답을 캐싱하여 이후 동일한 요청에 대해 새로운 요청을 서버에 보내지 않고 캐시된 응답을 반환함으로써 성능을 향상시킬 수 있습니다.

4. SSL 암호화 및 해독: 리버스 프록시는 클라이언트와 서버 간의 SSL 암호화를 처리할 수 있으며, 클라이언트와 서버 간의 암호화된 통신을 해독하여 내부 네트워크에서는 암호화되지 않은 형태로 전달할 수 있습니다.

5. 액세스 제어 및 모니터링: 리버스 프록시를 사용하여 특정 요청을 필터링하거나 차단함으로써 보안을 강화하고, 트래픽을 모니터링하여 네트워크 상태를 파악할 수 있습니다.

이러한 기능들은 웹 서비스의 성능, 가용성, 보안 등을 향상시키는 데 중요한 역할을 합니다.

 

Prerequisite
1. 이전글 [AWS] EC2, Nginx, Let's Encrypt를 통한 HTTPS 적용 (무료 도메인)에서 이어서 구축 진행
2. 테스트 용도의 애플리케이션 하나 설치 (Gitea 구축하기)
3. Public IP 할당, Inbound Port는 22, 80, 443 뿐만 아니라, 사용할 포트는 오픈 (Gitea는 3000)

 

HTTPS 적용 (Let's Encrypt)
웹 서버와 도메인, 테스트 애플리케이션까지 설치가 됐다면 인증서 발급을 진행하도록 하겠습니다.
// Key 생성
// 이미 인증서가 존재한다면 아래와 같이 나옵니다.
$ certbot --nginx -d {Public IP}.nip.io -d www.{Public IP}.nip.io -d gitea.{Public IP}.nip.io

Saving debug log to /var/log/letsencrypt/letsencrypt.log

You have an existing certificate that contains a portion of the domains you    
requested (ref: /etc/letsencrypt/renewal/{Public IP}.nip.io.conf)

It contains these names: {Public IP}.nip.io, www.{Public IP}.nip.io

You requested these names for the new certificate: {Public IP}.nip.io,        
www.{Public IP}.nip.io, gitea.{Public IP}.nip.io.

Do you want to expand and replace this existing certificate with the new       
certificate?
(E)xpand/(C)ancel: E
Renewing an existing certificate for {Public IP}.nip.io and 2 more domains

Successfully received certificate.
Certificate is saved at: /etc/letsencrypt/live/{Public IP}.nip.io/fullchain.pem
Key is saved at:         /etc/letsencrypt/live/{Public IP}.nip.io/privkey.pem
This certificate expires on 2024-09-10.
These files will be updated when the certificate renews.
Certbot has set up a scheduled task to automatically renew this certificate in the background.

Deploying certificate
Successfully deployed certificate for {Public IP}.nip.io to /etc/nginx/sites-enabled/default
Successfully deployed certificate for www.{Public IP}.nip.io to /etc/nginx/sites-enabled/default
Successfully deployed certificate for gitea.{Public IP}.nip.io to /etc/nginx/sites-enabled/default
Your existing certificate has been successfully renewed, and the new certificate has been installed.
 
// 인증서 확인
$ certbot certificates
Found the following certs:
  Certificate Name: {Public IP}.nip.io
    Serial Number: 3c0b84eda9102ca8e5276d9efa54c28ba3a
    Key Type: ECDSA
    Domains: {Public IP}.nip.io gitea.{Public IP}.nip.io www.{Public IP}.nip.io
    Expiry Date: 2024-09-10 04:54:53+00:00 (VALID: 89 days)
    Certificate Path: /etc/letsencrypt/live/{Public IP}.nip.io/fullchain.pem
    Private Key Path: /etc/letsencrypt/live/{Public IP}.nip.io/privkey.pem
    
// 성공적으로 Key가 생성되었는지 확인
$ ls /etc/letsencrypt/live/{Public IP}.nip.io
README  cert.pem  chain.pem  fullchain.pem  privkey.pem

 

Nginx Reverse Proxy 구축
// Certbot이 자동으로 Nginx에 HTTPS 설정
// Nginx를 Reverse Proxy로 사용할 것이니 경로를 수정해야 합니다.
// 아래와 같은 server 블록을 찾고, location 부분을 수정합니다.
$ vi /etc/nginx/sites-available/default

server {

        # SSL configuration
        #
        # listen 443 ssl default_server;
        # listen [::]:443 ssl default_server;
        #
        # Note: You should disable gzip for SSL traffic.
        # See: https://bugs.debian.org/773332
        #
        # Read up on ssl_ciphers to ensure a secure configuration.
        # See: https://bugs.debian.org/765782
        #
        # Self signed certs generated by the ssl-cert package
        # Don't use them in a production server!
        #
        # include snippets/snakeoil.conf;

        root /var/www/html;

        # Add index.php to the list if you are using PHP
        index index.html index.htm index.nginx-debian.html;
    server_name gitea.{Public IP}.nip.io; # managed by Certbot


        location / {
                proxy_set_header Host $host;
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                proxy_set_header X-Forwarded-Proto $scheme;
                proxy_set_header Upgrade $http_upgrade;
                proxy_set_header Connection "upgrade";
                proxy_set_header X-Real-IP $remote_addr;
                proxy_pass http://localhost:3000; # Gitea 서버 IP
        }
        
        # pass PHP scripts to FastCGI server
        #
        #location ~ \.php$ {
        #       include snippets/fastcgi-php.conf;
        #
        #       # With php-fpm (or other unix sockets):
        #       fastcgi_pass unix:/run/php/php7.4-fpm.sock;
        #       # With php-cgi (or other tcp sockets):
        #       fastcgi_pass 127.0.0.1:9000;
        #}

        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /\.ht {
        #       deny all;
        #}


    listen [::]:443 ssl; # managed by Certbot
    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/3.34.225.130.nip.io/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/3.34.225.130.nip.io/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot

}

// Nginx 재실행
$ sudo systemctl restart nginx

// 웹 브라우저에서 확인
https://{Public IP}.nip.io
https://www.{Public IP}.nip.io
https://gitea.{Public IP}.nip.io -> Gitea가 접속되면 성공

'Server' 카테고리의 다른 글

[Ubuntu] USB 연결 및 파일 복사(백업)  (0) 2024.06.26
[Nexus] Nexus를 통한 Private Image Registry 구축  (2) 2024.06.14
OAuth2.0이란?  (0) 2023.04.02
JWT(Json Web Token)란?  (0) 2023.04.01