使用 nginx 托管 vue.js 和 codeigniter

hosting vue.js and codeignitor with nginx

我在“/var/www/public_html/website.com/”中有 2 个文件夹 distapi_middleware

dist 文件夹包含我的前端生产代码。此文件夹是来自 /home/user/frontend/dist

的符号链接

api_middleware 文件夹包含 codeignitor 代码,我们将其用作前端的中间件以与我们的 erp 进行通信。此文件夹是来自 /home/user/api_middleware.

的符号链接

我想用 nginx 托管这两个代码。这是我想出的代码。

server {
  listen 443;
    ssl on;
    ssl_certificate /etc/ssl/website.com.crt; 
    ssl_certificate_key /etc/ssl/website.com.key;
    server_name website.com;
    access_log /var/log/nginx/nginx.vhost.access.log;
    error_log /var/log/nginx/nginx.vhost.error.log;

    index index.php index.html index.htm index.nginx-debian.html;

    location / {
       root /var/www/public_html/website.com/dist;
       try_files $uri $uri/ /index.html;
    }

    location /api_middleware {
       root /var/www/public_html/website.com;
       try_files $uri $uri/ /api_middleware/index.php?/$request_uri;
       client_max_body_size 100M;
    }

    location ~ \.php$ {
    include snippets/fastcgi-php.conf;
    fastcgi_pass unix:/run/php/php7.2-fpm.sock;
    fastcgi_read_timeout 300;
    }
}

导航到 website.com 有效。但是使用 website.com\api_middleware\<PARAMS> 的 api 调用返回 404

我做错了什么?

PS。使用 ubuntu 18.4.

我更新的工作代码:

server {
  listen 443;
    ssl on;
    ssl_certificate /etc/ssl/website.com.crt;
    ssl_certificate_key /etc/ssl/website.com.key;
    server_name website.com;
    access_log /var/log/nginx/nginx.vhost.access.log;
    error_log /var/log/nginx/nginx.vhost.error.log;
    root /var/www/public_html/website.com/dist;
    index index.php index.html index.htm index.nginx-debian.html;

    location /api_middleware {
        alias /var/www/public_html/website.com/api_middleware/;
        try_files $uri $uri/ /api_middleware/api_middleware/index.php?/$request_uri;
        client_max_body_size 100M;
    }

    location ~ /api_middleware/.+\.php$  {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/run/php/php7.2-fpm.sock;
        fastcgi_read_timeout 300;
    }
}

问题是使用多个 root 会干扰 nginx 访问我的第二个代码库的目录位置。

我使用 alias 更改位置以搜索我的第二个代码库,同时使用 root 设置我的第一个代码库的位置。

看看行 try_files $uri $uri/ /api_middleware/api_middleware/index.php?/$request_uri;。我在这里添加了 'api_middleware' 两次,即使 index.php 文件的位置是 /var/www/public_html/website.com/api_middleware/index.php 。这是必需的,因为 nginx 中有一个非常古老的错误。

最后,为了处理 php 文件,我将查找 php 文件的 URI 更改为 ~ /api_middleware/.+\.php$

参考:

  1. NGINX try_files + alias directives
  2. https://serverfault.com/questions/1035733/nginx-difference-between-root-and-alias
  3. https://serverfault.com/questions/684523/nginx-multiple-roots/684605