使用客户端应用程序路径:
/
/foo
/foo/bar
/foo/bar/baz
/foo/bar/baz/123
/tacos
/tacos/123
采用:
server {
listen 80;
server_name example.com;
root /var/www/example.com;
gzip_static on;
location / {
try_files $uri $uri/ /index.html;
}
# Attempt to load static files, if not found route to @rootfiles
location ~ (.+)\.(html|json|txt|js|css|jpg|jpeg|gif|png|svg|ico|eot|otf|woff|woff2|ttf)$ {
try_files $uri @rootfiles;
}
# Check for app route "directories" in the request uri and strip "directories"
# from request, loading paths relative to root.
location @rootfiles {
rewrite ^/(?:foo/bar/baz|foo/bar|foo|tacos)/(.*) /$1 redirect;
}
}
虽然@Adam-Waite 的答案适用于根级别的根和路径,但在位置上下文中使用 if 被认为是一种反模式,这在转换 Apache 样式指令时经常出现。请参阅:http ://wiki.nginx.org/IfIsEvil 。
其他答案不包括在我的用例中使用 react-router 和 HTML5 pushState 的类似 React 应用程序中具有目录深度的路由。当在“目录”(例如example.com/foo/bar/baz/213123
我的 index.html 文件)中加载或刷新路由时,将在相对路径中引用 js 文件并解析为example.com/foo/bar/baz/js/app.js
而不是example.com/js/app.js
.
对于目录深度超出第一级的情况,例如/foo/bar/baz
,请注意在 @rootfiles 指令中声明的目录的顺序:最长可能的路径需要先行,然后是下一个较浅的路径/foo/bar
,最后是/foo
.