Nginx location配置优化

应用场景: 访问domain.com/xxx,返回project/templates/xxx.html内容

原配置文件如下:

1
2
3
4
5
6
7
8
9
10
11
root /home/wayde/project/templates;
location /aaa {
try_files $uri /aaa.html;
}
location /bbb {
try_files $uri /bbb.html;
}
...
location / {
try_files /app.html;
}
  1. 方案1
1
2
3
4
5
6
7
root /home/wayde/project/templates;
location ~* ^/(\w+)/?.*$ {
try_files $uri /$1.html /app.html;
}
location / {
try_files $uri /app.html;
}
  1. 方案2
1
2
3
4
5
6
7
8
9
10
root /home/wayde/project/templates;
location ~* ^/(\w+)/?.*$ {
try_files $uri /$1.html /app.html;
}
location @other {
try_files $uri /app.html;
}
location / {
try_files $uri /app.html;
}
  1. 方案3
1
2
3
4
5
6
7
root /home/wayde/project/templates;
location ~* ^/(\w+)/?.*$ {
try_files $uri /$1.html /; #ubuntu nginx1.4.6不支持最后面的"/", nginx1.10.3以上版本支持支持
}
location / {
try_files $uri /app.html;
}