RadarURL

소프트웨어
2013.04.08 08:43

Nginx HttpRewriteModule

조회 수 3828 추천 수 0 댓글 0
?

단축키

Prev이전 문서

Next다음 문서

크게 작게 위로 아래로 댓글로 가기 인쇄
?

단축키

Prev이전 문서

Next다음 문서

크게 작게 위로 아래로 댓글로 가기 인쇄

Synopsis

This module makes it possible to change URI using regular expressions (PCRE), and to redirect and select configuration depending on variables.

If the directives of this module are given at the server level, then they are carried out before the location of the request is determined. If in that selected location there are further rewrite directives, then they also are carried out. If the URI changed as a result of the execution of directives inside location, then location is again determined for the new URI.

This cycle can be repeated up to 10 times, after which Nginx returns a 500 error.

[edit] Directives

[edit] break

Syntax: break
Default:
Context: server
location
if
Reference: break


Completes the current set of rules. Continue processing within the current location block but do not process any more rewrite directives.

Example:

if ($slow) {
  limit_rate  10k;
  break;
}

[edit] if

Syntax: if ( condition ) { ... }
Default:
Context: server
location
Reference: if


note: Before using if please see the if is evil page and consider using try_files instead.

Checks the truth of a condition. If the condition evaluates to true, then the code indicated in the curly braces is carried out and the request is processed in accordance with the configuration within the following block. The configuration inside the ifdirective is inherited from the previous level.

The condition can be:

  • the name of a variable; false values are: empty string ("", or any string starting with "0";
  • a comparison of a variable using the = and != operators;
  • pattern matching with regular expressions:
    • ~ performs a case-sensitive match
    • ~* performs a case-insensitive match (firefox matches FireFox)
    • !~ and !~* mean the opposite, "doesn't match"
  • checking for the existence of a file using the -f or !-f operators;
  • checking for the existence of a directory using -d or !-d;
  • checking for the existence of a file, directory or symbolic link using -e or !-e;
  • checking whether a file is executable using -x or !-x.

Parts of the regular expressions can be in parentheses, whose value can then later be accessed in the $1 to $9 variables. See Extracting matches.

Examples of use:

if ($http_user_agent ~ MSIE) {
  rewrite  ^(.*)$  /msie/$1  break;
}
 
if ($http_cookie ~* "id=([^;] +)(?:;|$)" ) {
  set  $id  $1;
}
 
if ($request_method = POST ) {
  return 405;
}
 
if ($slow) {
  limit_rate  10k;
}
 
if ($invalid_referer) {
  return   403;
}
 
if ($args ~ post=140){
  rewrite ^ http://example.com/ permanent;
}

The value of the built-in variable $invalid_referer is given by the directive valid_referers.

[edit] return

Syntax: return code [ text ]
return code URL
return URL
Default:
Context: server
location
if
Reference: return


This directive concludes execution of the rules and returns the status code indicated to client. It is possible to use any http return code, ranging in number from 0-999. Furthermore, nonstandard code 444 closes the connection without sending any headers.

[edit] rewrite

Syntax: rewrite regex replacement [ flag ]
Default:
Context: server
location
if
Reference: rewrite


This directive changes URI in accordance with the regular expression and the replacement string. Directives are carried out in order of appearance in the configuration file.

Flags make it possible to end the execution of rewrite directives.

If the replacement string begins with http:// then the client will be redirected, and any further rewrite directives are terminated.

Flags can be any of the following:

  • last - completes processing of current rewrite directives and restarts the process (including rewriting) with a search for a match on the URI from all available locations.
  • break - completes processing of current rewrite directives and non-rewrite processing continues within the current location block only.
  • redirect - returns temporary redirect with code 302; it is used if the substituting line begins with http://
  • permanent - returns permanent redirect with code 301

- Note that outside location blocks, last and break are effectively the same.

Example:

rewrite  ^(/download/.*)/media/(.*)\..*$  $1/mp3/$2.mp3  last;
rewrite  ^(/download/.*)/audio/(.*)\..*$  $1/mp3/$2.ra   last;
return   403;

But if we place these directives in location /download/, then it is necessary to replace flag "last" by "break", otherwise Nginx will hit the 10 cycle limit and return error 500:

location /download/ {
  rewrite  ^(/download/.*)/media/(.*)\..*$  $1/mp3/$2.mp3  break;
  rewrite  ^(/download/.*)/audio/(.*)\..*$  $1/mp3/$2.ra   break;
  return   403;
}

If in the line of replacement arguments are indicated, then the rest of the request arguments are appended to them. To avoid having them appended, place a question mark as the last character:

  rewrite  ^/users/(.*)$  /show?user=$1?  last;

Note: for curly braces( { and } ), as they are used both in regexes and for block control, to avoid conflicts, regexes with curly braces are to be enclosed with double quotes (or single quotes). For example, to rewrite URLs like:

/photos/123456

to:

/path/to/photos/12/1234/123456.png

use the following (note the quotes enclosing the regex):

rewrite  "/photos/([0-9]{2})([0-9]{2})([0-9]{2})" /path/to/photos/$1/$1$2/$1$2$3.png;

If you specify a ? at the end of a rewrite then Nginx will drop the original $args (arguments). When using $request_uri or $uri&$args you should specify the ? at the end of the rewrite to avoid Nginx doubling the query string.

Example using $request_uri in a rewrite from www.example.com to example.com

server {
   server_name www.example.com;
   rewrite ^ http://example.com$request_uri? permanent;
}

Also rewrite operates only on path, not parameters. To rewrite a URL with parameters to another URL, use this instead:

if ($args ~ post=100){
  rewrite ^ http://example.com/new-address.html? permanent;
}

Note that the $args variable is not decoded, unlike URIs during location matching.

Also note that named subexpressions (?<name>) should be used when accessing variables from a map using regular expressions (patterns begininng with ~) because the map runs on demand and will override $1 (even when named subexpressions are used in the map).

[edit] rewrite_log

syntax: rewrite_log on | off

default: rewrite_log off

context: http, server, if-in-server, location, if-in-location

variables: no


When enabled, outputs information about rewrites to the error log at notice level.

[edit] set

Syntax: set variable value
Default:
Context: server
location
if
Reference: set


Directive establishes value for the variable indicated. As the value it is possible to use a text, variables and their combination.

You can use set to define a new variable. Note that you can't set the value of a $http_xxx header variable.

[edit] uninitialized_variable_warn

Syntax: uninitialized_variable_warn on | off
Default: on
Context: http
server
location
if
Reference: uninitialized_variable_warn


Enables or disables logging of warnings about noninitialized variables.

[edit] Internal implementation

Internally, the rewrite directives are compiled at the time the configuration file is loaded into internal codes, usable during the request by the interpreter.

This interpreter is a simple stack virtual machine. For example, the directive:

location /download/ {
  if ($forbidden) {
    return   403;
  }
  if ($slow) {
    limit_rate  10k;
  }
  rewrite  ^/(download/.*)/media/(.*)\..*$  /$1/mp3/$2.mp3  break;
}

will be compiled into this sequence:

  variable $forbidden
  checking to zero
  recovery 403
  completion of entire code
  variable $slow
  checking to zero
  checkings of regular expression
  copying "/"
  copying $1
  copying "/mp3/"
  copying $2
  copying ".mp3"
  completion of regular expression
  completion of entire sequence

Note that there is no code for directive limit_rate, since it does not refer to module ngx_http_rewrite_module. The "if" block exists in the same part of the configuration as the "location" directive.

If $slow is true, then what's inside the "if" block is evaluated, and in this configuration limit_rate it is equal to 10k.

Directive:

  rewrite  ^/(download/.*)/media/(.*)\..*$  /$1/mp3/$2.mp3  break;

It is possible to reduce the sequence, if in the regular expression we include the first slash inside the parentheses:

  rewrite  ^(/download/.*)/media/(.*)\..*$  $1/mp3/$2.mp3  break;

then the sequence will appear like this:

  checking regular expression
  copying $1
  copying "/mp3/"
  copying $2
  copying ".mp3"
  completion of regular expression
  completion of entire code

[edit] References

Original Documentation

PCRE Man Page in Plain Text


RegexOne» Learn regular expressions with simple, interactive examples.

RegexPal — a JavaScript regular expression tester

 

출처 : http://wiki.nginx.org/HttpRewriteModule

?

공부 게시판

공부에 도움되는 글을 올려주세요.

List of Articles
번호 분류 제목 글쓴이 날짜 조회 수
공지 [공지] 공부 게시판 입니다. 처누 2003.08.18 928098
2473 웹서버,WAS http를 https로 리다이렉트하는 여러가지 방법 new JaeSoo 2025.09.10 0
2472 웹서버,WAS SSL인증서 없이 HTTPS에서 HTTP로 되돌리기 new JaeSoo 2025.09.10 2
2471 웹서버,WAS [SSL] win-acme, Let's encrypt로 무료 SSL 인증서 발급 new JaeSoo 2025.09.10 0
2470 웹서버,WAS [SSL] Windows 10에서 Let's Encrypt로 SSL 인증서 무료 발급받기 new JaeSoo 2025.09.10 0
2469 웹서버,WAS 무료로 https SSL/TLS 인증서를 발급받을 수 있는 인증 기관 new JaeSoo 2025.09.10 0
2468 웹서버,WAS 아파치 서버에 https SSL 인증서 적용하는 방법 (apache httpd) new JaeSoo 2025.09.10 0
2467 웹서버,WAS 아파치2(Apache2) SSL HTTPS 적용하기 new JaeSoo 2025.09.10 0
2466 웹서버,WAS 아파치 웹서버에 멀티 도메인에 대한 80, 443 포트 설정하는 방법 newfile JaeSoo 2025.09.10 0
2465 소프트웨어 Google Photo 대신 Immich를 써보자 file JaeSoo 2025.08.07 126
2464 연애 남자 혹은 여자 진국 팁 JaeSoo 2025.07.24 116
2463 기타 MBTI검사 16가지 유형 “간단 명료”하게 정리! file JaeSoo 2025.07.01 132
2462 소프트웨어 [사진관리] PhotoPrism vs LibrePhoto 비교 소감 JaeSoo 2025.05.19 14
2461 네트워크 MDF실, TPS실, EPS실 이게 뭘까? file JaeSoo 2025.04.15 33
2460 업무 알아두면 좋은 직장인 용어 정리 file JaeSoo 2025.04.15 37
2459 건강 감기·독감·코로나19의 차이점, 신촌연세병원과 함께 알아봅시다. file JaeSoo 2025.01.08 29
2458 생활 집주인이 전세 보증금을 돌려주지 않을 때 JaeSoo 2024.11.29 26
2457 자동차 자전거 타이어 종류 및 추천 2편 (승차감 타이어, 국토종주!) JaeSoo 2024.10.15 53
2456 자동차 오도바이 센타 사장들은 어떤 브랜드를 싫어하고 좋아할까? [출처] 오도바이 센타 사장들은 어떤 브랜드를 싫어하고 좋아할까?|작성자 바이크신 file JaeSoo 2024.10.15 78
2455 윈도우즈 윈도우 자동 로그온 설정이 보이지 않을 때 조치사항 JaeSoo 2024.08.16 203
2454 모바일 갤럭시S22 시리즈에서 SKT LTE 무제한 핫스팟 쓰는 방법! (SKT LTE 요금제만 해당!) JaeSoo 2024.08.12 234
Board Pagination Prev 1 2 3 4 5 6 7 8 9 10 ... 124 Next
/ 124


즐겨찾기 (가족)

JAESOO's HOMEPAGE


YOUNGAE's HOMEPAGE


장여은 홈페이지


장여희 홈페이지


장여원 홈페이지


즐겨찾기 (업무)

알리카페 홀릭

숭실대 컴퓨터 통신연구실 (서창진)

말레이시아 KL Sentral 한국인 GuestHouse


즐겨찾기 (취미)

어드민아이디

유에코 사랑회

아스가르드 좋은사람/나쁜사람

JServer.kr

제이서버 메타블로그

재수 티스토리


즐겨찾기 (강의, 커뮤니티)

재수 강의 홈페이지


한소리


VTMODE.COM


숭실대 인공지능학과


숭실대 통신연구실


베너