标签归档:nginx配置

nginx配置备记

先来写一个最常用的配置:location

Syntax:	location [ = | ~ | ~* | ^~ ] uri { ... }
location @name { ... }
Default:	—
Context:	server, location
来源:http://nginx.org/en/docs/http/ngx_http_core_module.html#location

nginx配置中占大头,可以对请求进行各种处理
location的生效顺序:先匹配字符串的,后匹配正则的,字符串按照最长匹配来匹配,但正则只要匹配成功就直接返回,如果在正则表达式中没有匹配,则用在字符串匹配中匹配的最合适的那个规则,但还有一个例外是:
如果字符串匹配使用了”^~”,如果匹配到则不会再去匹配正则
匹配方式: 
空 开头匹配
=  完全匹配
~ 正则匹配(区分大小写)
~* 正则匹配(不区分大小写)
^~ 开头匹配(若匹配正则将被忽略)

正则表达式:
nginx采用的是PCRE正则,文档一大堆,直接查就行,和平时使用的正则是一样的。

location的Context为server,location,因此location是可以嵌套的。

再看一下常用的配置: rewrite

Syntax:	rewrite regex replacement [flag];
Default:	—
Context:	server, location, if
来源:http://nginx.org/en/docs/http/ngx_http_rewrite_module.html

rewrite主要是改写当前url,当然是可以选择显式或者隐式改写,以满足多种需求:比如跳转,静态化,转发等
规则比较简单 会正则表达式就可以,匹配到的内容可以在replacement中使用,例如:
rewrite ^/article/(\d+)\.htm /article.htm?id=$1;