如何为同时包含客户端和服务器代码的项目设置 nginx 重写规则?

How do I set an nginx rewrite rule for my project that contains both client and server code?

我的文件结构如下所示

demo
|+ build
| |+ images
| | |- logo.png
| |+ static
|   |+ css
|   | |- style.css
|   |+ js
|   |- index.html
|+ controllers
  |+ api
    |- users.php

这是我想如何设置我的 apache 虚拟主机的地图。

url path
https://demo.com/ build/index.html
https://demo.com/users build/index.html
https://demo.com/users/16 build/index.html
https://demo.com/images/logo.png build/images/logo.png
https://demo.com/static/css/style.css build/static/css/style.css
https://demo.com/api/users controllers/api/users

编辑

经过多次尝试,我创建了这样的 apache 虚拟主机,它有点管用。这是正确的方法吗?我在服务器端没有太多经验。

现在我必须用 nginx 实现同样的效果,因为我的真实服务器正在使用 nginx。我如何对 nginx 设置做同样的事情?

<VirtualHost *:80> 
    DocumentRoot "/Users/hao/Projects/demo" 
    ServerName demo.dev
    Options FollowSymLinks 
    RewriteEngine on

    RewriteRule ^(?!/?api/)(.*\.\w+)$ /build/ [L] 
    RewriteRule ^(?!/?api/|/?$) /build/index.html [L] 
    RewriteRule ^/?api/(.*)$ /controllers/api/ [QSA,NE,L]
</VirtualHost>

看来您可以只使用 /Users/hao/Projects/demo/build 作为您的根目录。假设你在/Users/hao/Projects/demo/controllers/api目录下只有PHP个文件,你可以试试下面的配置:

server {
    server_name demo.dev;
    root /Users/hao/Projects/demo/build;
    index index.html;
    location / {
        try_files $uri /index.html;
    }
    location ~ ^/api/.+\.php$ {
        root /Users/hao/Projects/demo/controllers;
        try_files $uri =404;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $request_filename;
        fastcgi_pass <socket path or ip:port to PHP-FPM daemon here>;
    }
}