可以使用前缀"^~"来禁止匹配到字符串后,再去检查正则表达式,匹配到url后,将停止查询.
使用前缀"="可以进行精确的url匹配,如果找到匹配的uri,则停止查询,例如"location=/",只能匹配到"/",而"/test.html"则不能被匹配.
正则表达式的匹配,按照它们在配置文件中的顺序进行,写在前面的优先.
Location = / {
#仅仅匹配 /
[configuration A]
}
Location / {
#匹配任何以/开头的查询,但是正则表达式及较长的字符串(/bbs/)将被优先匹配.
[configuration B]
}
Location ^~ /images/ {
#匹配任何以/images/开头的字符串,并且停止搜索,所以正则表达式将不会被检查.
[configuration C]
}
Location ~* .(gif|jpg|jpeg)$ {
#匹配以.gif、.jpg、.jpeg结尾的任何请求,但是,/images/内的请求将使用configuration c的配置
[configuratoin D]
}
请求处理匹配结果示例:
/ -> configuration A;
/documents/document.html -> configuration B;
/images/1.gif -> configuration c;
/documents/1.jpg -> configuration D;
例1:域名跳转
输入www.sina.com,跳转到www.sohu.com
server {
listen 80;
server_name www.sina.com;
access_log logs/sina.access.log main;
location / {
root /web/sina;
index index.html index.htm;
if (-e $request_filename){
# -e 是否存在
rewrite ^/ http://www.sohu.com/ permanent;
# ^/ 域名以/开头。//www.sina.com ,也可以写为.* 任意都跳转
}
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {








