웹서버 분류

Nginx proxy cache를 이용하여 이미지 캐시서버 구축하기 (Ubuntu, CentOS 8)

컨텐츠 정보

  • 27,126 조회
  • 4 댓글
  • 0 추천
  • 목록

본문

3232235777_l6INWzyY_7da2fac1b2ff831e80a1c410f0cc60032af84c56.png



1. Ubuntu 20.04 LTS


https://nginx.org/en/linux_packages.html


위 링크에 있는 방식으로 Nginx를 설치하고 


ufw나 iptables에 의한 80, 443 포트를 열어줍니다.


SSL 인증서도 적절하게 설치해줍니다.



/etc/nginx/sites-available/default.conf


파일을 열어서



proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=static:100m max_size=10g inactive=30d;
proxy_cache_key "$scheme$request_method$host$request_uri";


server {
        listen 443 ssl http2;
        listen [::]:443 ssl http2;
        server_name cdn.example.com; # 이미지 캐시서버 도메인
        server_tokens off;


        location ~* \.(?:css|js|gif|png|jpg|jpeg|mp4|webm)$ {
                valid_referers none blocked example.com; # 본서버 외 불펌금지
                if ($invalid_referer) {
                    return   403;
                }
                proxy_pass https://example.com; # 본서버 도메인
                proxy_cache_valid 200 301 302 600m;
                proxy_cache static;
                proxy_cache_use_stale  error timeout updating http_500 http_502 http_503 http_504;
                proxy_cache_revalidate on;
                proxy_cache_lock       on;
                proxy_ignore_headers Set-Cookie;
                access_log off;
                add_header My-Cache-Status $upstream_cache_status;
                add_header my-ray  "KR";
                sendfile on;
                tcp_nopush on;
                tcp_nodelay on;
                keepalive_timeout 65;
                }


        location / { 
                return   403;
        }


        ssl_certificate ssl/fullchain.pem; #자신의 인증서 경로로..
        ssl_certificate_key ssl/privkey.pem; #자신의 인증서 경로로..
        ssl_trusted_certificate ssl/chain.pem; #자신의 인증서 경로로..


        ssl_stapling on;
        ssl_stapling_verify on;
        resolver 8.8.8.8 8.8.4.4 valid=300s;
        resolver_timeout 10s;
}


위와 같이 수정하고,



sudo service nginx restart


위 명령어로 재시작해줍니다.


적용이 끝났습니다.



이제 본서버에 가서 css,js,gif,png,jpg,jpeg,mp4,webm파일의 URL을 캐시서버의 도메인으로 수정해주면 됩니다.


(1) 본서버가 Nginx라면



sub_filter_once off;
    sub_filter 'https://mydomain.com/data/file/' 'https://cdn.mydomain.com/data/file/';
    sub_filter 'https://mydomain.com/data/editor/' 'https://cdn.mydomain.com/data/editor/';


위와 같이 정적파일이 있는 폴더를 대치시키면 편합니다.


Nginx를 재시작하면 적용 끝입니다.



(2) 본서버가 Apache라면



sudo a2enmod substitute


위 명령어로 substitute 모듈을 활성화한 후



<Location "/">
	AddOutputFilterByType SUBSTITUTE text/html
	Substitute "s|https://mydomain.com/data/file/|https://cdn.mydomain.com/data/file/|i"
	Substitute "s|https://mydomain.com/data/editor/|https://cdn.mydomain.com/data/editor/|i"
</Location>


위와 같이 정적파일이 있는 폴더를 대치시키면 편합니다.


Apache를 재시작하면 적용 끝입니다.



2. CentOS 8


https://nginx.org/en/linux_packages.html


위 링크의 방식대로 Nginx를 설치합니다.


SSL 인증서도 설치해줍니다.



sudo firewall-cmd --zone=public --permanent --add-service=http



sudo firewall-cmd --zone=public --permanent --add-service=https


위와 같이 firewall 설정에서 80, 443 포트를 열어줍니다.


iptables 규칙이 걸려있다면 따로 잡아주세요.



/etc/nginx/default.conf


위 파일을 열어서


server { } 안의 내용을



proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=static:100m max_size=10g inactive=30d;
proxy_cache_key "$scheme$request_method$host$request_uri";


server {
        listen 443 ssl http2;
        listen [::]:443 ssl http2;
        server_name cdn.example.com; # 이미지 캐시서버 도메인
        server_tokens off;


        location ~* \.(?:css|js|gif|png|jpg|jpeg|mp4|webm)$ {
                valid_referers none blocked example.com; # 본서버 외 불펌금지
                if ($invalid_referer) {
                    return   403;
                }
                proxy_pass https://example.com; # 본서버 도메인
                proxy_cache_valid 200 301 302 600m;
                proxy_cache static;
                proxy_cache_use_stale  error timeout updating http_500 http_502 http_503 http_504;
                proxy_cache_revalidate on;
                proxy_cache_lock       on;
                proxy_ignore_headers Set-Cookie;
                access_log off;
                add_header My-Cache-Status $upstream_cache_status;
                add_header my-ray  "KR";
                sendfile on;
                tcp_nopush on;
                tcp_nodelay on;
                keepalive_timeout 65;
                }


        location / { 
                return   403;
        }


        ssl_certificate ssl/fullchain.pem; #자신의 인증서 경로로..
        ssl_certificate_key ssl/privkey.pem; #자신의 인증서 경로로..
        ssl_trusted_certificate ssl/chain.pem; #자신의 인증서 경로로..


        ssl_stapling on;
        ssl_stapling_verify on;
        resolver 8.8.8.8 8.8.4.4 valid=300s;
        resolver_timeout 10s;
}


위의 내용으로 바꿔줍니다.



sudo systemctl restart nginx


수정 후 위 명령어로 nginx를 재시작해줍니다.


이미지 캐시서버 구축이 끝났습니다.



이제 본서버에 가서 css,js,gif,png,jpg,jpeg,mp4,webm파일의 URL을 캐시서버의 도메인으로 수정해주면 됩니다.


(1) 본서버가 Nginx라면



sub_filter_once off;
    sub_filter 'https://mydomain.com/data/file/' 'https://cdn.mydomain.com/data/file/';
    sub_filter 'https://mydomain.com/data/editor/' 'https://cdn.mydomain.com/data/editor/';


위와 같이 정적파일이 있는 폴더를 대치시키면 편합니다.


Nginx를 재시작하면 적용 끝입니다.



(2) 본서버가 Apache라면



sudo a2enmod substitute


위 명령어로 substitute 모듈을 활성화한 후



<Location "/">
	AddOutputFilterByType SUBSTITUTE text/html
	Substitute "s|https://mydomain.com/data/file/|https://cdn.mydomain.com/data/file/|i"
	Substitute "s|https://mydomain.com/data/editor/|https://cdn.mydomain.com/data/editor/|i"
</Location>


위와 같이 정적파일이 있는 폴더를 대치시키면 편합니다.


Apache를 재시작하면 적용 끝입니다.




Centos 8에 적용 후, 502 Bad Gateway가 떴을 때 


캐시서버에 SSH로 접속 후



sudo getenforce


위 명령어를 내린 후 



Enforcing


위와 같이 나오면



sudo setsebool -P httpd_can_network_connect true


위 명령어로 Outbound를 풀어줍니다.



sudo systemctl restart nginx


위 명령어로 Nginx를 재시작해줍니다.




참고 사이트


https://nginx.org/en/linux_packages.html


https://www.runit.cloud/2020/05/centos-8-nginx-1.18-install.html


https://www.joinc.co.kr/w/man/12/proxy


https://jojoldu.tistory.com/60


https://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_cache_path


https://serverfault.com/questions/819423/reverse-proxy-nginx-bad-gateway

관련자료

  • 서명
    우성짱의 NAS를 운영하고 있습니다.

    저의 즐거움이 여러분의 즐거움이면 좋겠습니다.

댓글 4

궁금이님의 댓글

안녕하세요.
만약에 example.com 도메인뿐만 아니라
a.example.com/~jpg //b.example.com/~jpg
와 같이 앞에 서브도메인만 다르게 되어있는 본서버의 이미지를 img.example.com 으로 대치시키고 싶으면 어떤식으로 구성을 해야할까요..?
본서버 도메인을 *.example.com 과 같이 해도 적용해도 될지 궁금합니다..!

우성짱님의 댓글의 댓글

*는 해보질 않아서 잘 모르겠습니다.

이론적으론 sub_filter 구문을 계속 추가해서 넣는게 정확할 듯 합니다.

다이어그램빌런님의 댓글

혹시 이 내용 다이어그램으로 보여주실 수 있을까요? 외부 url 이미지를 nginx 캐시 서버에 캐싱하려고 하는데 어떤 흐름으로 가는지 설명해주시면 좋을 것 같네요ㅠㅠ
전체 43 / 1 페이지
RSS

최근글


새댓글


알림 0