静态和 PHP 文件的 NGINX 配置

Bob*_*Bob 5 html php nginx

我正在尝试配置 nginx 来提供静态文件和 PHP 文件。我的配置不起作用。我想要以下本地文件夹结构:

src/static/  -> contains HTML, CSS, JS, images etc
src/api/     -> contains PHP files for a small REST service
Run Code Online (Sandbox Code Playgroud)

如果我访问http://mysite.local我希望获得 /static 文件夹中的文件。如果我访问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
Run Code Online (Sandbox Code Playgroud)

以下配置适用于静态文件,但不适用于 api 文件。如果我访问其中一个 API 路径,则会收到 404 错误。

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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Ric*_*ith 4

最初的问题是块root中的指令location /api,该指令不应包含位置组件,因为它会作为 URI 的一部分附加,因此:

location /api {
    root /var/www/mysite/src;
    ...
}
Run Code Online (Sandbox Code Playgroud)

/var/www/mysite/src/api/index.php当与 URI 一起出现时,将产生本地路径/api/index.php。有关详细信息,请参阅此文档

try_files规则不会按照您在示例中指定的方式重写 URI。如果您确实需要将 URI 的最终路径作为查询字符串呈现给/api/index.php您,则需要使用rewrite.

最简单的解决方案(如果您不需要从该位置提供静态内容)是将您的替换为try_files

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

    location ~ \.php$ { ... }
}
Run Code Online (Sandbox Code Playgroud)

否则,使用命名位置:

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

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

有关详细信息,请参阅