https://www.wsgvet.com/web/243

 

위 링크에 최종 정리했습니다.

 

Ubuntu 20.04 LTS와 CentOS 8에 적용하는 방법입니다.

 

---

 

기진곰의 설명을 듣고 만들어보니 잘 되네요. 

 

속도도 php에 비해서 더 빠르고 안정적이네요.

 

1. 이미지 캐시서버에 Nginx를 설치한다.

 

설정파일에 밑과 같이 넣는다. (SSL 인증서은 미리 발급해둔다.)

 

proxy_cache_path /var/www/html levels=1:2 keys_zone=static:100m max_size=10g inactive=30d use_temp_path=off;
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 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 "access-control-allow-headers" "Origin, Referer, User-Agent, DNT, Upgrade-Insecure-Requests, X-Requested-With"
                add_header "access-control-allow-method" "GET"
                add_header "access-control-allow-origin" "https://example.com" # 본서버 도메인
                add_header "access-control-max-age" "864000"
                add_header My-Cache-Status $upstream_cache_status;
                add_header my-ray  "KR";
                }

        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;
}

 

cdn.example.com은 이미지 캐시서버의 도메인으로, example.com은 원래 서버의 도메인으로 수정 후

 

Nginx를 재시작한다.

 

 

2. 본서버의 img나 동영상 또는 css, js 파일의 경로를 이미지 캐시서버의 도메인으로 바꾼다.

 

끝입니다.

 

 

직접 해보니 재밌네요.

 

기진곰님 감사합니다.

 

도커로 캐시서버 구축 스크립트 만들어 봐야겠네요.

우성짱

profile
반갑습니다. 우성짱입니다.
Nginx와 Docker에 관심이 많습니다.
홈페이지 : https://www.wsgvet.com
깃 허 브 : https://github.com/woosungchoi
  • profile

    잘 구성하셨네요. 몇 가지 개선점을 제안드리자면

    - 이미지 파일이 아닌 경우 일괄적으로 404 또는 403 처리하는 location / { } 블록이 있으면 좋겠습니다.

    - 이미지 파일만 제공하는 서버에서 Access-Control-Allow-* 헤더는 의미가 없습니다.

    - /var/www/html은 일반적으로 사이트 운영에 사용하는 기본 경로인데, 거기에 캐시파일을 잔뜩 만들어놓으면 이미지 캐시서버를 다른 용도로 병용하는 경우 불편을 유발하거나 캐시파일이 외부에 노출될 수 있습니다. 그러나 /var/www 자체는 엄연히 웹서버 용도로 사용하라고 있는 것이니, 그 아래에 별도로 하위폴더를 만들어 쓴다면 표준에도 맞고 안전할 것 같네요.

    - 임시 폴더와 캐시 폴더를 동일한 디스크에 넣는다면 use_temp_path=off를 설정할 필요는 없습니다. 완전히 다운로드되지 않은 임시 파일이 사용자에게 전송되는 등의 불상사를 막을 수 있습니다.

  • profile profile
    감사합니다. 업데이트 해보도록 하겠습니다.

    생각지도 못한 부분들이 많네요 ㅎㅎ
  • profile profile
    proxy_cache_path /var/cache 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 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;
    }

     

    이정도 작업하면 괜찮겠죠?

  • profile
    날마다 빠르게 잘 하시네요!
    https://blog.lael.be/wp-content/uploads/2020/07/saa.png 이 이미지가 캐시되는지 확인해보세요.
  • profile profile
    넵. 해보니깐 잘 되네요!
  • ?
    참고가 되었습니다. 감사합니다~
  • ? profile
    넵! 잘 쓰세요~