본문으로 바로가기 본문 바로가기
WIKI 기술 지식 베이스

리라이트 규칙 변환하기 (Converting rewrite rules)

원문 보기 위키 갱신

Apache의 .htaccess 파일에 익숙한 분들이 nginx로 옮겨올 때 흔히 겪는 리라이트 규칙 변환 예시를 다뤄요. 올바른 관점으로 규칙을 옮기는 방법을 알려드릴게요.

출처: 문서

본문

메인 사이트로의 리다이렉트

공유 호스팅 시절에 Apache의 .htaccess 파일만으로 모든 것을 설정하던 분들은 보통 다음 규칙을:

RewriteCond  %{HTTP_HOST}  example.org
RewriteRule  (.*)          http://www.example.org$1

다음과 같이 옮기곤 해요:

server {
    listen       80;
    server_name  www.example.org  example.org;
    if ($http_host = example.org) {
        rewrite  (.*)  http://www.example.org$1;
    }
    ...
}

이것은 잘못되고, 번거롭고, 비효율적인 방법이에요. 올바른 방법은 example.org용 별도 server를 정의하는 거예요:

server {
    listen       80;
    server_name  example.org;
    return       301 http://www.example.org$request_uri;
}

server {
    listen       80;
    server_name  www.example.org;
    ...
}

0.9.1 이전 버전에서는 리다이렉트를 다음과 같이 할 수 있어요:

    rewrite      ^ http://www.example.org$request_uri?;

또 다른 예시가 있어요. "example.com도 아니고 www.example.com도 아닌 모든 것"이라는 "거꾸로 된" 논리 대신에:

RewriteCond  %{HTTP_HOST}  !example.com
RewriteCond  %{HTTP_HOST}  !www.example.com
RewriteRule  (.*)          http://www.example.com$1

예를 들어 example.com, www.example.com, 그리고 "그 외 모든 것"을 간단히 정의해야 해요:

server {
    listen       80;
    server_name  example.com www.example.com;
    ...
}

server {
    listen       80 default_server;
    server_name  _;
    return       301 http://example.com$request_uri;
}

0.9.1 이전 버전에서는 리다이렉트를 다음과 같이 할 수 있어요:

    rewrite      ^ http://example.com$request_uri?;

Mongrel 규칙 변환

전형적인 Mongrel 규칙은:

DocumentRoot /var/www/myapp.com/current/public

RewriteCond %{DOCUMENT_ROOT}/system/maintenance.html -f
RewriteCond %{SCRIPT_FILENAME} !maintenance.html
RewriteRule ^.*$ %{DOCUMENT_ROOT}/system/maintenance.html [L]

RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^(.*)$ $1 [QSA,L]

RewriteCond %{REQUEST_FILENAME}/index.html -f
RewriteRule ^(.*)$ $1/index.html [QSA,L]

RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule ^(.*)$ $1.html [QSA,L]

RewriteRule ^/(.*)$ balancer://mongrel_cluster%{REQUEST_URI} [P,QSA,L]

이렇게 변환되어야 해요:

location / {
    root       /var/www/myapp.com/current/public;

    try_files  /system/maintenance.html
               $uri  $uri/index.html $uri.html
               @mongrel;
}

location @mongrel {
    proxy_pass  http://mongrel;
}

더 알아보기 (Learn more)