2014-12-04 47 views
1

我想要nginx與基於PushState的uri一起使用,由react-router處理。 一切工作正常,直到我嘗試F5在第二級烏里example.com/MyApp/usersNginx重寫pushstate靜態資源不會加載

我的靜態資源位於example.com/MyApp/resources。 問題是,只要我嘗試直接訪問(或F5)users的視圖,nginx就會嘗試加載example.com/MyApp/users/resources中的資源。

這裏是我的nginx的conf:

location ~ ^/MyApp/ { 
    try_files $uri /MyApp/index.html last; 
} 

我是新來nginx的,所以我真的不知道如何一切正常......

編輯:

我改變了我conf對此:

location/{ 
    if (!-e $request_filename){ 
     rewrite ^(.*)$ /MyApp/index.html break; 
    } 
} 

現在訪問example.com/MyApp/users作品,但example.com/MyApp/users/沒有。

回答

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; 
} 
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; 
    } 
} 

此配置在pushState「目錄」內工作,如example.com/foo/bar/baz/213123和r在js/app.jsexample.com/js/app.js而不是example.com/foo/bar/baz/js/app.js之間的相對路徑上解析靜態文件。

對於超過第一級如/foo/bar/baz目錄深度的情況下,請注意@rootfiles指令聲明的目錄順序:最長的可能路徑需要去第一,其次是下一個較淺的路徑/foo/bar終於/foo

See this related answer to a similar question regarding Backbone.