首页 > 解决方案 > 从 Laravel 中的子目录 Nginx 中删除 index.php

问题描述

我试图在同一个域下运行两个代码库,一个静态 vue-cli 站点和一个 Laravel 后端 api。

静态站点将用于前端,这将查询 laravel 代码库。我无法从我的 laravel 网址中删除 index.php。

我的文件系统如下;

/var/www/site/frontend/dist/index.html <-- static homepage
                           /another.html <-- another static page
/var/www/site/backend/api/index.php <-- api access

对我的 api 的请求看起来像

/api <-- laravel landing page, only for debugging
/api/autocomplete/artist/{artistName}
/api/autocomplete/artist/{artistName}/album/{albumTitle}

我想我已经很接近了,但还不够,我拥有的最好的是 l Laravel 登陆页面,但是每当我添加路由参数时,我都会得到 404,下面是我的配置;

server {
    listen 80 default_server;

    root /var/www/site/frontend/dist;

    index index.html index.htm index.php;

    server_name _;

    # Make index.php in /api url unnecessary
    location /api {
      alias /var/www/site/backend/api;

      try_files $uri $uri/ /index.php?r=$is_args$args;

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

    }

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

标签: laravelnginx

解决方案


您需要使用^~修饰符,否则您的其他location ~ \.php$块优先于错误的文档根目录。有关详细信息,请参阅此文档

您不需要使用alias文档根的最后一部分匹配位置 - 这可以简化事情alias并且在一起使用时try_files会出现问题

语句的最后一个元素try_files应该是一个 URI,它需要包含位置前缀。有关更多信息,请参阅此文档

例如:

location ^~ /api {
    root /var/www/site/backend;
    try_files $uri $uri/ /api/index.php?r=$is_args$args;

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

推荐阅读