Cloud/AWS

[AWS] 프로젝트 초기 설정 (2) - Nginx와 Reverse Proxy 설정

aeeazip 2023. 11. 7. 22:40

목차


1. Nginx 설정

2. Nginx에서의 정적 컨텐츠 호스팅

3. Nginx 설정 파일에서의 location 블록

4. Reverse Proxy 설정

 

 

 

 

1. Nginx (웹 서버) 설정


 

원격 접속 한 터미널에서 아래 명령어를 입력해 Nginx를 설치한다.

$ sudo apt update
$ sudo apt upgrade -y
$ sudo apt install nginx -y
$ systemctl nginx status

 

nginx 상태가 active라면 브라우저에서 EC2 아이피 주소로 접속 시 Welcome to nginx 가 뜬다!

(만약 아래 화면이 보이지 않는다면 EC2의 보안그룹에 TCP 80번 포트가 anywhere로 설정이 되어있나 확인하고, nginx가 제대로 설치 되었는지 확인하기!)

 

 

 

 

 

2. Nginx에서의 정적 컨텐츠 호스팅


Nginx는 웹 서버이므로, Nginx의 설정 파일을 읽어 웹 서버가 실행된다.

Ubuntu를 기준으로 Nginx의 설정 파일/etc/nginx/sites-available 디렉토리에서 default 이다.

 

$ cd /etc/nginx/sites-available
$ cat default

 

 

default 파일을 열면 아래와 같은 내용을 확인할 수 있다.

 

 

##
# You should look at the following URL's in order to grasp a solid understanding
# of Nginx configuration files in order to fully unleash the power of Nginx.
# https://www.nginx.com/resources/wiki/start/
# https://www.nginx.com/resources/wiki/start/topics/tutorials/config_pitfalls/
# https://wiki.debian.org/Nginx/DirectoryStructure
#
# In most cases, administrators will remove this file from sites-enabled/ and
# leave it as reference inside of sites-available where it will continue to be
# updated by the nginx packaging team.
#
# This file will automatically load configuration files provided by other
# applications, such as Drupal or Wordpress. These applications will be made
# available underneath a path with that package name, such as /drupal8.
#
# Please see /usr/share/doc/nginx-doc/examples/ for more detailed examples.
##

# Default server configuration
#
server {
        listen 80 default_server;
        listen [::]:80 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 _;

        location / {
                # First attempt to serve request as file, then
                # as directory, then fall back to displaying a 404.
                try_files $uri $uri/ =404;
        }

        # pass PHP scripts to FastCGI server
        #
        #location ~ \.php$ {
        #       include snippets/fastcgi-php.conf;
        #
        #       # With php-fpm (or other unix sockets):
        #       fastcgi_pass unix:/var/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;
        #}
}


# Virtual Host configuration for example.com
#
# You can move that to a different file under sites-available/ and symlink that
# to sites-enabled/ to enable it.
#
#server {
#       listen 80;
#       listen [::]:80;
#
#       server_name example.com;
#
#       root /var/www/example.com;
#       index index.html;
#
#       location / {
#               try_files $uri $uri/ =404;
#       }
#}

 

 

 

여기서 root, index가 의미하는 바는 다음과 같다.

  • root = 정적 컨텐츠를 찾는 시작 디렉토리
  • index = 기본적인 요청에 대해 index 뒤의 파일을 찾아 웹 상으로 보여준다

 

실제 아래 경로로 이동해 파일 목록을 보면 index.nginx-debian.html 파일이 있는 것을 확인 가능하다.

 

 

$ cd /var/www/html
$ ls

 

 

 

index.nginx-debian.html 파일 내부는 아래와 같은데 문서 내용을 보면 EC2 IP주소:80 포트로 요청을 보냈을 때 응답으로 오는 HTML 문서임을 알 수 있다.

 

 

<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
    body {
        width: 35em;
        margin: 0 auto;
        font-family: Tahoma, Verdana, Arial, sans-serif;
    }
</style>
</head>
<body>
<h1>Welcome to nginx!</h1>
<p>If you see this page, the nginx web server is successfully installed and
working. Further configuration is required.</p>

<p>For online documentation and support please refer to
<a href="http://nginx.org/">nginx.org</a>.<br/>
Commercial support is available at
<a href="http://nginx.com/">nginx.com</a>.</p>

<p><em>Thank you for using nginx.</em></p>
</body>
</html>

 

 

 

즉, root /var/www/html 을 통해 정적 컨텐츠를 찾아낼 시작 디렉토리를 지정하고

index 를 통해 기본 요청이 들어온 경우 어떤 파일을 내보낼지 설정하며

 

/ 요청에 대해

/var/www/html/index.nginx-debian.html 을 응답으로 준 것이다!

 

 

 

 

3. Nginx 설정 파일에서의 location 블록


/etc/nginx/sites-available/default 에 아래 블록을 추가한다.

기존 location / { } 밑에 새로운 location 블록을 추가해주면 되고, 내용은 다음과 같다.

 

location /mission3 {
                root /var/www;
                index mission3.html;
                try_files $uri $uri/ /mission3.html =404;
        }

 

 

 

이후 /var/www로 이동해서 아래의 명령어를 수행한다.

 

$ sudo systemctl restart nginx <- nginx 설정 변경이 되었으니 재실행 해야함
$ sudo cd /var/www
$ sudo mkdir mission3
$ sudo cd mission3
$ sudo vi mission3.html

 

 

mission3.html 의 내용은 다음과 같다.

 

<h1>Hi! This is Jay!</h1>

 

 

간단히 적어주고 nginx의 status가 active 중인 것을 확인했다면

/mission3로 접속했을 때 다음과 같은 화면이 보인다!

 

 

 

즉, location 블록이 의미하는 바는 다음과 같다.

  • /y 요청이 들어오면
  • /x/y에서 파일을 찾아라! 라는 뜻

 

location /y{
	root /x
}

 

 

 

 

4. Reverse Proxy 설정


/etc/nginx/sites-available/default에 다음과 같은 내용을 추가한다.

 

 

location /was {
		proxy_pass <http://localhost:8080>;
}

 

 

이후 sudo systemctl restart nginx로 nginx를 재시작해주고 ip주소/was로 접속하면 502 에러가 난다.

 

 

 

 

당연히 502 에러가 발생하는게 맞다! 현재 8080 포트를 가진 프로세스가 없기 때문이다.

만약 8080 포트를 가진 프로세스가 동작 중이라면 /was 요청이 들어왔을 때 http://localhost:8080 요청의 결과를 보여줄 것이다!