Nginx location 的用法

Nginx location 配置能够使Nginx根据URI不同的参数做出不同的行为。

官方解释:

Generally, the configuration file may include several server blocks distinguished by ports on which they listen to and by server names. Once nginx decides which server processes a request, it tests the URI specified in the request’s header against the parameters of the location directives defined inside the server block.

配置规则

优先级依次降低

  1. = 精确匹配
  2. ^~ 表示普通字符前缀匹配,如果该选匹配,只匹配该选项,不匹配别的选项,一般用来匹配目录
  3. ~ 正则匹配,区分大小写
  4. ~* 正则匹配,不区分大小写

示例

/ 表示完全匹配

location / {
    echo '匹配所有请求。';
}

=精确匹配nginx

location = /nginx {
    echo '=精确匹配nginx。';
}

^~前缀匹配nginx

location ^~ /nginx {
    echo '^~前缀匹配nginx。';
}

~正则区分大小写匹配图片

location ~ \.(jpg|png|gif)(){
    echo '~正则匹配图片。';
}

~*正则不区分大小写匹配图片

location ~* \.(jpg|png|gif)(){
    echo '~正则匹配图片。';
}

测试

安装 Nginx echo 模块
命令行运行

# / 完全匹配
curl learn_nginx.com/

# = 精确匹配
curl learn_nginx.com/nginx

# ^~ 前缀匹配
curl learn_nginx.com/nginx_test

# ~ 正则匹配
curl learn_nginx.com/111.jpg

# ~* 正则匹配,区分大小写
curl learn_nginx.com/111.PNG

完整的nginx配置

server{
	listen 80;
	index index.html index.php;
	server_name learn_nginx.com;
	root /var/www/jack/dev/learn_nginx;
	access_log /var/www/jack/dev/learn_nginx/log;


	location / {
	    echo '匹配所有请求。';
	}

	location = /nginx {
	    echo '=精确匹配nginx。';
	}

	location ^~ /nginx {
	    echo '^~前缀匹配nginx。';
	}

	location ~ \.(jpg|png|gif)(){
	    echo '~正则匹配图片。';
	}

	location ~* \.(JPG|PNG|GIF)(){
	    echo '~*正则匹配图片。';
	}
}
JackSun

JackSun

I'm a coder.

You may also like...