apache 웹 서버 캐싱 설정하기

inhalin·2023년 8월 24일
0

시작하기

  • 우분투에서는 apache2로 설치
sudo apt install apache2 -y # 설치
  • 실행, 상태 확인, 종료, 재실행
systemctl start apache2 # 실행
systemctl status apache2 # 상태 확인
systemctl stop apache2 # 종료
systemctl restart apache2 # 재실행
systemctl reload apache2 # 재로드(설정파일 변경시)
  • 설정 파일 에러 확인
apachectl configtest # 설정 파일 오류 확인

# 정상
Syntax OK

# 오류
AH00526: Syntax error on line 8 of /etc/apache2/...
...
The Apache error log may have more information.

캐싱 설정하기

apache의 기본 캐싱값

  • 헤더에 Cache-Control, Expires 둘다 없으면 캐시된 엔티티의 freshness lifetime 기본값은 1시간이다.
  • 응답 헤더에 Expires 가 없고 Last-Modified 값만 있으면 휴리스틱 캐싱을 한다.
  • 휴리스틱 캐싱 기본 식 = (Date - Last-Modified) * 0.1

캐싱 설정 방식

  • apache 설정 파일 추가 또는 .htaccess 파일 추가
  • 둘 중 한가지만 해주면 되고 작성되는 내용을 동일하다.

1. apache 설정 파일 추가

  • 참고
    • a2enconf 명령어는 /etc/apache2/conf-available 에 있는 설정 파일의 심링크를 /etc/apache2/conf-enabled 에 자동으로 생성한다.
    • a2enmod 명령어는 /etc/apache2/mods-available 에 있는 모듈의 심링크를 /etc/apache2/mods-available 에 자동으로 생성한다.
cd /etc/apache2/conf-available # 설정파일 디렉토리로 이동
vi custom-cache-control.conf # 커스텀 설정 파일 만들기
# custom-cache-control.conf

<FilesMatch "\.(apk|plist|ipa)$">
    Header set Cache-Control "no-store"
    Header unset ETag
    FileETag None
</FilesMatch>
  • FilesMatch 에는 설정 적용할 파일을 정규표현식으로 작성한다.
    • 위에서는 확장자가 .apk, .plist, .ipa 에 해당하는 파일들이 적용 대상이 된다.
a2enconf custom-cache-control # 추가한 커스텀 설정 파일 사용하기
apachectl configtest # 설정파일 오류 없는지 확인
systemctl restart apache2 # apache 재실행

⛔️ apachectl configtest 시에 Syntax 에러 나는 경우

설정 파일을 추가하고 apachectl configtest 명령어 실행시 아래와 같은 오류 메시지가 출력될 수 있다.

AH00526: Syntax error on line 8 of /etc/apache2/conf-enabled/custom-cache-control.conf:
Invalid command 'Header', perhaps misspelled or defined by a module not included in the server configuration
Action 'configtest' failed.
The Apache error log may have more information.

headers 모듈이 활성화되어 있지 않아서 그런 것이므로 a2enmod 명령어로 headers 모듈을 활성화해준다.

a2enmod headers

성공적으로 모듈이 활성화가 된 경우 아래와 같이 출력된다.

Enabling module headers.
To activate the new configuration, you need to run:
  systemctl restart apache2

다시 설정파일 오류가 없는지 확인한다.

apachectl configtest
Syntax OK # 이렇게 나오면 정상

모듈을 활성화/비활성화 하고나면 apache를 재실행 해줘야 한다.

systemctl restart apache2

2. .htaccess 파일 추가

cd /var/www/html/
vi .htaccess
# 내용은 custom-cache-control.conf 파일과 동일

apachectl configtest # 설정파일 오류 확인

결과

캐싱 비활성화 적용된 경우

  • Cache-Control: no-store
  • ETag 없음

기본값 그대로 적용된 경우

  • Cache-Control 없음
  • ETag 있음

참고

0개의 댓글