Apache 리다이렉트 설정 가이드

목차

Apache 리다이렉트는 주로 .htaccess 파일과 mod_rewrite 모듈로 설정합니다. 메인 서버 설정에 접근할 수 없는 공유 호스팅에서 특히 유용합니다.

.htaccess 기본

.htaccess는 Apache의 디렉토리별 설정 파일입니다. 사이트 루트에 배치하면 Apache가 자동으로 읽습니다. 파일명이 점으로 시작하므로 Unix 시스템에서는 숨김 파일입니다.

mod_rewrite 활성화

# Ubuntu/Debian
sudo a2enmod rewrite
sudo systemctl restart apache2

# CentOS/RHEL — /etc/httpd/conf/httpd.conf에서 주석 해제:
LoadModule rewrite_module modules/mod_rewrite.so

.htaccess 오버라이드 허용

<Directory /var/www/html>
    AllowOverride All
</Directory>

Redirect 디렉티브

가장 간단한 방법 — 정규식 불필요:

# 301 영구 리다이렉트
Redirect 301 /old-page.html https://example.com/new-page.html

# 302 임시 리다이렉트
Redirect 302 /sale https://example.com/promo

# 사이트 전체를 새 도메인으로 리다이렉트
Redirect 301 / https://new-domain.com/

💡 Redirect의 한계

Redirect 디렉티브는 간단하지만 정규식이나 조건 분기를 지원하지 않습니다. 더 복잡한 처리에는 RewriteRule을 사용하세요.

RewriteRule

RewriteEngine On

# HTTP → HTTPS
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L]

# non-www → www
RewriteCond %{HTTP_HOST} ^example\.com$ [NC]
RewriteRule ^(.*)$ https://www.example.com/$1 [R=301,L]

자주 사용하는 플래그

RewriteCond

다음 RewriteRule이 실행되기 전에 충족해야 하는 조건:

# 모바일 사용자 리다이렉트
RewriteCond %{HTTP_USER_AGENT} "android|iphone|ipad" [NC]
RewriteRule ^(.*)$ https://m.example.com/$1 [R=302,L]

# 쿼리 문자열 기반 리다이렉트
RewriteCond %{QUERY_STRING} ^id=([0-9]+)$
RewriteRule ^article$ /post/%1? [R=301,L]

일반적인 시나리오

HTTPS + www 강제

RewriteEngine On
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} ^example\.com$ [NC]
RewriteRule ^(.*)$ https://www.example.com/$1 [R=301,L]

.html 확장자 제거

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.html -f
RewriteRule ^(.+)$ $1.html [L]

RewriteCond %{THE_REQUEST} ^[A-Z]+\ /(.+)\.html
RewriteRule ^ /%1 [R=301,L]

WordPress 퍼머링크

# BEGIN WordPress
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
# END WordPress

흔한 실수

500 Internal Server Error

거의 확실히 .htaccess의 구문 오류입니다. Apache 오류 로그를 확인하세요:

tail -f /var/log/apache2/error.log

리다이렉트 루프

# ❌ 루프 — 재매칭을 중단하는 조건 없음
RewriteRule ^(.*)$ https://example.com/ [R=301,L]

# ✅ HTTPS 조건 추가
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://example.com/ [R=301,L]

쿼리 문자열 손실

# ❌ 쿼리 문자열이 사라짐
RewriteRule ^old-page$ /new-page [R=301,L]

# ✅ QSA 플래그로 유지
RewriteRule ^old-page$ /new-page [R=301,L,QSA]

디버깅

# 리라이트 로그 활성화 (Apache 2.4)
LogLevel alert rewrite:trace3

# curl로 테스트
curl -I http://example.com/old-page
curl -IL http://example.com/old-page

또는 301check.com으로 전체 리다이렉트 체인을 시각화할 수 있습니다.