Nginx - 在位置重写

Nginx - rewriting in locations

我想在我的 nginx 服务器上有 2 个不同的位置 (Ubuntu 16.04)。我的 HTML 页面 (page.com; page.com/sth/sth2) 在 /var/www/html 中的一个和我的 PHP API (page.com/api; page.com/api/v1/test) 在 /var/www/api。每个对 API 的请求都应该转到 api.php 文件(我在那里有路由)。

我正在尝试这样做,目前 page.com/api/api.php 正在工作,但是 page.com/api/v1/test 没有(我得到 404未找到错误)。

root /var/www/html;

location ^~ /api/ {
    root /var/www;
    rewrite ^(.*)$ var/www/api/api.php last;

    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_param SCRIPT_FILENAME /var/www/api/api.php;
        fastcgi_pass unix:/run/php/php7.0-fpm.sock;
    }
}

location / {
    index index.html;
    try_files $uri $uri/ =404;
}

location ~ /\.ht {
    deny all;
}

只需将 /api/ 位置块替换为以下内容:

location /api/ {
    root /var/www/api;
    include snippets/fastcgi-php.conf;
    fastcgi_param SCRIPT_NAME /api.php;
    fastcgi_param SCRIPT_FILENAME $document_root/api.php;
    fastcgi_pass unix:/run/php/php7.0-fpm.sock;
}

然后所有这些请求都转到 api.php,您可以在那里处理路由,就像您似乎所做的那样。

你可能也不需要这部分:

location ~ /\.ht {
    deny all;
}

因为 Nginx 不会对 .htaccess 文件做任何事情 - 所以没有安全风险。