我正在努力让nginx
使用由react-router
处理的基于pushstate的uri。
一切正常,直到我在第二级uri example.com/MyApp/users
尝试F5。
我的静态资源位于example.com/MyApp/resources
。
问题是,每当我尝试直接(或F5)访问example.com/MyApp/users/resources
的视图时,nginx都会尝试在users
中加载我的资源。
这是我的nginx conf:
location ~ ^/MyApp/ {
try_files $uri /MyApp/index.html last;
}
我是nginx的新手,所以我真的不知道一切是如何运作的......
编辑:
我改变了我的想法:
location / {
if (!-e $request_filename){
rewrite ^(.*)$ /MyApp/index.html break;
}
}
现在访问example.com/MyApp/users
有效但example.com/MyApp/users/
没有。
答案 0 :(得分:2)
使用客户端应用程序路径:
/
/foo
/foo/bar
/foo/bar/baz
/foo/bar/baz/123
/tacos
/tacos/123
使用nginx配置:
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;
}
}
此配置将在example.com/foo/bar/baz/213123
等pushState“目录”中运行,并解析相对路径上的静态文件,如js/app.js
到example.com/js/app.js
,而不是example.com/foo/bar/baz/js/app.js
。
对于目录深度超出第一级别的情况,例如/foo/bar/baz
,请注意@rootfiles指令中声明的目录的顺序:最长的路径需要先行,然后是下一个较浅的路径{{ 1}},最后是/foo/bar
。
See this related answer to a similar question regarding Backbone.
答案 1 :(得分:0)
我认为你必须做这样的事情:
location ~ ^/MyApp/ {
# First attempt to serve request as file, then
# as directory, then fall back to displaying a 404.
try_files $uri $uri/ /index.html =404;
}
location ~ ^/MyApp/resources {
# First attempt to serve request as file, then
# as directory, then fall back to displaying a 404.
try_files $uri $uri/ /resources/index.html =404;
}