一、语法规则
location [=|^~|~|~*|!~|!~*] uri {...}
或
location @name {...} #nginx内部跳转。
location匹配的目标字符串是nginx的变量$request_uri(不包含query string)。
二、各修饰符的含义:
1、基于平面字符串匹配:
location = /uri 表示将$request_uri精确匹配到/uri,完全匹配才有效,并且停止正则测试。
location ^~ /uri 对$request_uri路径进行前缀匹配,意味着只要以/uri开头的URL都将匹配到,并且停止正则测试。
location /uri 不带任何修饰符,也表示前缀匹配,但是会继续使用正则测试,若正则匹配成功则使用正则的location,否则使用自身。
(常见的location / 也是属于这类匹配,由于其以/开头,所以任何没有匹配到的请求最终都会回归于此。)
平面字符串匹配基于长度优先的匹配顺序,比如 location /test 与 location /testing 同时存在,则优先使用 location/testing。
2、基于正则表达式的匹配:
location ~ pattern 表示区分大小写的正则匹配。
location ~* pattern 表示不区分大小写的正则匹配。
location !~ pattern 区分大小写不匹配的正则。
location !~* pattern 不区分大小写不匹配的正则。
正则表达式的匹配使用权高于无修饰的字符串匹配,例如:
location /test/ 与 location ~ /test/ 同时存在,则取location ~ /test/ 。所以为了能让字符串匹配优先,需要使用修饰符=或者^~。
正则表达式之间则按书写顺序优先使用,例如:
location ~ /test 与 location ~ /test/ 匹配example.com/test时使用前者。
3、内部跳转
location @name nginx内部跳转。
比如:
location /hello/{
error_page 404 @rule_err;
}
location @rule_err{
#rules;
}
三、常见的配置
PHP配置:
server {
listen 80; #listen 80 default_server; 可以增加default_server参数使其成为默认的server段。也就是HTTP_HOST不匹配到任何server_name的时候由此server处理。
server_name example.org www.example.org;
root /data/www; #root指令也可以放在Location段中
location / {
index index.html index.php; #当匹配到/并且index.html不存在时,nginx会继续向后查找index.php, 发现index.php文件之后便会发起内部重定向,于是就匹配到了后面的location ~ \.php$。然而有个疑问,如果index.html存在的话,nginx发起内部重定向但是没有找到与index.html匹配的location,于是又回到了“location /”段,那么这不是死循环了么。实际测试是并不会出现这种情况。
}
location ~* \.(gif|jpg|png)$ {
expires 30d;
}
location ~ \.php$ {
fastcgi_pass localhost:9000;
fastcgi_param SCRIPT_FILENAME
$document_root$fastcgi_script_name; #向CGI传入参数,$document_root等于配置中的root, $fastcgi_script_name等于$request_uri。
include fastcgi_params;
}
}
参考:
http://nginx.org/en/docs/http/request_processing.html
WebSocket配置:
http {
map $http_upgrade $connection_upgrade {
default upgrade;
'' close;
}
server {
...
location /chat/ {
proxy_pass http://backend;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $connection_upgrade;
}
}
参考:
http://nginx.org/en/docs/http/websocket.html
tryfiles指令:
location / {
try_files $uri $uri/index.html = 404;
}
#如果$uri找不到,则定向到$uri/index.html, 如果$uri/index.html不存在会发生死循环,此时加上=404可以避免掉。