21

Javascript アプリで管理するベースの URI 処理をnginx使用しようとしています。pushStatebackbone.js

現在、1 つのレベルで URI にアクセスしています。はうまく機能しますが、バックボーンのドキュメントに記載されているexample.com/usersなどの 2 レベル以上の URI は機能しません。example.com/users/all

たとえば、/documents/100 のルートがある場合、ブラウザーがその URL に直接アクセスした場合、Web サーバーはそのページを提供できる必要があります。

そのため、nginx の書き換えオプションに精通しているわけではありませんがrewrite ^ /index.html;、すべてを自分の にリダイレクトするようなことができると確信していindex.htmlますが、必要な同じサーバーに保存されている最終的な静的ファイル (画像、javascript、および css) を失う可能性があります。アクセスできるようにします。

では、これを機能させるには、以下に示す現在の構成で代わりに何をすべきでしょうか?

server {
    listen   80;
    server_name  example.com;

    location / {
        root   /var/www/example.com;
        try_files $uri /index.html;
    }

}
4

6 に答える 6

33

私はこの解決策に行き着きました:

server {

    listen 80;
    server_name example.com;
    root /var/www/example.com;

    # Any route containing a file extension (e.g. /devicesfile.js)
    location ~ ^.+\..+$ {
        try_files $uri =404;
    }

    # Any route that doesn't have a file extension (e.g. /devices)
    location / {
        try_files $uri /index.html;
    }

}

このようにして、ファイルが見つからない場合でも、少なくとも適切な 404 エラーが発生します。

于 2015-03-05T19:49:48.010 に答える
19

これが私がアプリケーションに対して行ったことです。「/」で終わるすべてのルート (それ自身のルートを除く) が提供されindex.htmlます。

  location ~ ^/.+/$ {
    rewrite .* /index.html last;
  }

route にプレフィックスを付けることもできます:

Backbone.history.start({pushState: true, root: "/prefix/"})

その後 :

  location ~ ^/prefix/ {
    rewrite .* /index.html last;
  }

または、ケースごとにルールを定義します。

于 2012-02-08T13:22:54.527 に答える
0

ajaxリクエストAPIが存在する可能性があるので、この場合は以下が適しています。

server {
    listen 80;
    server_name example.com;
    root /var/www/example.com;

    # Any route containing a file extension (e.g. /devicesfile.js)
    location ~ ^.+\..+$ {
        try_files $uri =404;
    }

    # Any route that doesn't have a file extension (e.g. /devices)
    location / {
        try_files $uri /index.html;
    }

    # The location block above provides the shortest prefix, of length one, 
    # and so only if all other location blocks fail to provide a match, 
    # this block will be used.

    # Ajax api starts with /v1/ will be proxied
    location /v1/ {
        proxy_pass http://proxy;
    }
}
于 2016-05-04T15:06:02.483 に答える