2016-03-22 24 views
2

静的ファイルとPHPファイルを提供するようにnginxを設定しようとしています。私が持っている設定は機能していません。私は、次のローカルフォルダ構造をしたい:私はhttp://mysite.localを訪問静的ファイルとPHPファイルのNGINX設定

src/static/ -> contains HTML, CSS, JS, images etc 
src/api/  -> contains PHP files for a small REST service 

場合、私は/静的フォルダからファイルを提供することにしたいです。私がhttp://mysite.local/apiにアクセスした場合、私はAPI PHPファイルを提供したいと思います。私はapiへのリクエストを書き直し、index.phpファイルに送りたいと思っています。

いくつかの例:

http://mysite.local/test.html     -> served from src/static/test.html 
http://mysite.local/images/something.png  -> served from src/static/images/something.png 
http://mysite.local/css/style.css    -> served from src/static/css/style.css 

http://mysite.local/api/users     -> served from src/api/index.php?users 
http://mysite.local/api/users/bob    -> served from src/api/index.php?users/bob 
http://mysite.local/api/biscuits/chocolate/10 -> served from src/api/index.php?biscuits/chocolate/10 

以下の設定は、APIファイルの静的ファイルに対して動作しますが、ありません。 APIパスの1つにアクセスすると、404エラーが返されます。

location /api { 
    root /var/www/mysite/src; 
    ... 
} 

がローカルになり:

server { 
    listen  80; 
    server_name mysite.local; 
    access_log /var/log/nginx/mysite.access.log main; 
    error_log /var/log/nginx/mysite.error.log debug; 


    location/{ 
     index index.html; 
     root /var/www/mysite/src/static; 
     try_files $uri $uri/ =404; 
    } 

    location /api { 
     index index.php; 
     root /var/www/mysite/src/api; 
     try_files $uri $uri/ /index.php?$query_string; 

     location ~ \.php$ { 
      try_files  $uri = 404; 
      fastcgi_pass 127.0.0.1:9000; 
      fastcgi_index index.php; 
      fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; 
      include  fastcgi_params; 
     } 
    } 
} 

答えて

1

初期問題がので、これはURIの一部として添付につれて位置成分を含むべきではないlocation /apiブロック内root指令は、ありますURI /api/index.phpが提示されたときの/var/www/mysite/src/api/index.phpのパス。詳細については、this documentを参照してください。

try_filesルールでは、指定したとおりにURIが書き換えられません。クエリ文字列として/api/index.phpに提示するURIの最終パスが本当に必要な場合は、rewriteを使用する必要があります。

最も簡単な解決策は、(あなたがその場所から静的なコンテンツを提供する必要がない場合)を交換することで、あなたのtry_filesで:

location /api { 
    ... 
    try_files $uri $uri/ @rewrite; 

    location ~ \.php$ { ... } 
} 
location @rewrite { 
    rewrite ^/api/(.*)$ /api/index.php?$1 last; 
} 

参照:それ以外の場合は

location /api { 
    ... 
    rewrite ^/api/(.*)$ /api/index.php?$1 last; 

    location ~ \.php$ { ... } 
} 

、名前の場所を使用詳細についてはthisおよびthisを参照してください。

+0

非常に有益な回答をいただきありがとうございます。主な問題は、/ apiロケーションブロックのルートの定義です。 – Bob