在没有子域的子文件夹中安装多个laravel项目

时间:2016-04-04 13:37:14

标签: php .htaccess laravel nginx

我已经尝试过搜索这个问题,但它与我的不同,所以我在这里发布。我正在尝试使用nginx创建一个Web服务器来托管子文件夹中的多个laravel项目。这是我的 labs 服务器。所以我想让我的项目像这样:

  • domain.com/project1
  • domain.com/project2
  • domain.com/project3

我正在为每个项目复制以下nginx location块(我不知道这里发生了什么,我只是从互联网上复制而且它有效):

location ^~ /project1/ {
        alias /home/web/project1/public;
        try_files $uri $uri/ @project1;

    location ~ \.php {
        fastcgi_pass                    unix:/var/run/php5-fpm.sock;
        fastcgi_index                   index.php;
        include                         /etc/nginx/fastcgi_params;
        fastcgi_param                   SCRIPT_FILENAME "/home/web/project1/public/index.php";
    }

}

location @project1 {
     rewrite /avm/(.*)$ /project1/index.php?/$1 last;
}

我的laravel应用程序中的RESTful路由如下:     

/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the controller to call when that URI is requested.
|
*/

Route::get('/', ['middleware' => 'auth','uses' => 'HomeController@index'])->name('home');

// Authentication
Route::get('auth/login', 'Auth\AuthController@getLogin');
Route::post('auth/login', 'Auth\AuthController@authenticate');
Route::get('auth/logout', 'Auth\AuthController@getLogout');

// Administração
Route::group(['prefix' => 'administracao', 'middleware' => 'auth'], function() {
    Route::resource('filiais', 'FiliaisController');
    Route::resource('precos', 'PrecosController');
    Route::resource('funcionarios', 'FuncionariosController');
    Route::resource('cargos', 'CargosController');
    Route::resource('vendedores', 'VendedoresController');
});

// Comercial
Route::group(['prefix' => 'comercial', 'middleware' => 'auth'], function() {
    Route::resource('clientes', 'ClientesController');
    Route::resource('fichas', 'FichasController');
});

// Operacional
Route::group(['prefix' => 'operacional', 'middleware' => 'auth'], function() {
    Route::resource('agenda', 'AgendaController');
    Route::resource('os', 'OsController');
    Route::resource('ambientes', 'AmbientesController');
    Route::resource('processos', 'ProcessosController');
    Route::get('relatorios', 'RelatoriosController@index');

    Route::group(['prefix' => 'processo', 'middleware' => 'auth'], function() {
        Route::get('create', 'ProcessoController@create');
        Route::get('index', 'ProcessoController@index');

        Route::post('{os}/parse', 'ProcessoController@parse');

        Route::get('{os}', 'ProcessoController@principal');
        Route::match(['get', 'post'], '{os}/detalhe', 'ProcessoController@detalhe');
        Route::get('{os}/duplicidades', 'ProcessoController@duplicidades');
        Route::get('{os}/restantes', 'ProcessoController@restantes');
        Route::match(['get', 'post'], '{os}/auditoria', 'ProcessoController@auditoria');
        Route::match(['get', 'post'], '{os}/operadores', 'ProcessoController@operadores');
        Route::match(['get', 'post'], '{os}/divergencia', 'ProcessoController@divergencia');
        Route::match(['get', 'post'], '{os}/finalizar', 'ProcessoController@finalizar');
        Route::get('{os}/excluir/{setor}', 'ProcessoController@destroy');
    });
});

虽然它进入商务逻辑(保存到数据库等)似乎有用(页面显示等),但它似乎有很多错误。例如,当我尝试在网址http://domain.com/project1/administracao/funcionarios中创建新员工时,它会向我显示错误:SQLSTATE[42S22]: Column not found: 1054 Unknown column '/administracao/funcionarios' in(它有点预先添加了一些网址)

当我设置像project1.domain.com这样的子域时,一切正常。但我不想为每个项目创建一个子域,我希望它在子文件夹url中工作。有可能吗?

8 个答案:

答案 0 :(得分:1)

我已经使用简单的符号链接在另一个站点的“子文件夹”中成功运行了Laravel 5.4项目。

Nginx配置中没有时髦的特殊重写规则。没有副本和粘贴项目的部分。没有提到路线中的子文件夹。只是一个常规的L​​aravel 5项目整齐地包含在服务器上的某个地方,并且从主站点的文档根目录到它的公共文件夹的符号链接。

/var/www/domain.com/public/project1 --> /var/www/project1/public

所有路线都有效!

在编写视图时,您必须在asset()辅助函数中包装客户端资产的路径,这样HTML中的路径将包含子文件夹,浏览器可以找到它们。

<!-- Styles -->
<link href="{{ asset('css/app.css') }}" rel="stylesheet">

但这样做并不会使您的代码变得不那么灵活,因为如果您在不通过子文件夹访问它的环境中运行该网站,它就可以正常工作,因为asset()适用于地址栏包含的内容。

答案 1 :(得分:0)

我认为问题可能出在您的nginx.conf文件中。试试这个:

location ^~ /project1 {
        alias /home/web/project1/public;
        try_files $uri $uri/ @project1;

    location ~ \.php {
        fastcgi_pass     unix:/var/run/php5-fpm.sock;
        fastcgi_index    index.php;
        include          /etc/nginx/fastcgi_params;
    }

}

location @project1 {
    rewrite /project1/(.*)$ /project1/index.php?/$1 last;
}

另外,请确保/home/web/project1/不在您的网络根目录中。

这就是说,我们不建议在子文件夹中运行Laravel。在子域中更容易。

我从this gist得到了这个建议的基本想法。

答案 2 :(得分:0)

不完全确定解决方案,但我认为你应该尝试这些:

  • 首先:在url文件中正确设置config/app.php
  • 其次:查看public/web.config文件。问题可能是这些配置会覆盖你的nginx。考虑更改<action type="Rewrite" url="project1/index.php" />并查看它返回的内容。

在最后一个例子中,var_dump模型并寻找它的来源。

答案 3 :(得分:0)

你试过这个配置吗?

https://gist.github.com/tsolar/8d45ed05bcff8eb75404

我会尽快测试明天我有时间在我的环境中复制你的情况。

答案 4 :(得分:0)

有一个简单的解决方案&#34;我想让它在子文件夹url中工作。有可能吗?&#34;。

步骤
 1.在主域公用文件夹中创建文件夹。  你需要创建3个文件夹
家用/网络/公共/ PROJECT1
家用/网络/公共/项目2
家用/网络/公共/项目3

 2.在每个项目文件夹中,您需要粘贴laravel应用程序的公共文件夹的内容

(来自您的 Laravel 项目)project1 / public / {contents} - 将此复制到 - &gt;(托管服务器)home / web / public / project1 / {contents}

  1. 将公共根目录之外的其余laravel项目上传,并授予该文件夹的写入权限。

  2. 现在打开(托管服务器)public / project1 / index.php 更新这两个字段

  3. 要求__DIR __。&#39; /../../ PROJECTONE / bootstrap / autoload.php&#39;;

    $ app = require_once __DIR __。&#39; /../../ PROJECTONE / bootstrap / app.php&#39;;

答案 5 :(得分:0)

尝试这样的事情....我在我的服务器上使用了.conf

server {
    listen  80;
    root /vagrant;
    index index.html index.htm index.php app.php app_dev.php;

    server_name 192.168.33.10.xip.io;

    access_log /var/log/nginx/vagrant.com-access.log;
    error_log  /var/log/nginx/vagrant.com-error.log error;

    charset utf-8;

    location ~project(\d*)/((.*)\.(?:css|cur|js|jpg|jpeg|gif|htc|ico|png|html|xml))$ {
        rewrite project(\d*)/((.*)\.(?:css|cur|js|jpg|jpeg|gif|htc|ico|png|html|xml))$ /project$1/public/$2 break;
    }

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

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

    location = /favicon.ico { log_not_found off; access_log off; }
    location = /robots.txt  { access_log off; log_not_found off; }

    error_page 404 /index.php;

    location ~ \.php$ {
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_pass unix:/var/run/php5-fpm.sock;
        fastcgi_index index.php;
        include fastcgi_params;
        set $laravel_uri $request_uri;
        if ($laravel_uri ~ project(\d*)(/?.*)$) {
            set $laravel_uri $2;
        }
        fastcgi_param REQUEST_URI $laravel_uri;
        fastcgi_param LARA_ENV local; # Environment variable for Laravel
        fastcgi_param HTTPS off;
    }
    location ~ /\.ht {
        deny all;
    }
}

答案 6 :(得分:0)

最近我遇到了同样的问题。我想要

但我讨厌每次添加新项目时都要修改nginx conf。

这是我想出的:

# Capture $project from /$projectname/controller/action
map $request_uri $project {

    ~^/(?<captured_project>[a-zA-Z0-9_-]+)/? $captured_project;
    default / ;
}

server {

    listen 11.22.33.44:80;

    server_name customerdemo.example.com www.customerdemo.example.com;

    # Use $project/public as root
    root /sites/customerdemo.example.com/$project/public;

    # Use index.php as directory index
    index index.php;

    # Include the basic h5bp config set (see https://github.com/h5bp/server-configs-nginx)
    include h5bp/basic.conf;

    # Process /projectname/the/rest/of/the/url
    location ~ ^/([^/]+)/(.*) {

        # Save the rest of the URL after project name as $request_url
        set $request_url /$2;


        # If the saved url refers to a file in public folder (a static file), serve it,
        # else redirect to index.php, passing along any ?var=val URL parameters
        try_files $request_url /index.php?$is_args$args;

    }

    # Process any URL containing .php (we arrive here through previous location block)
    # If you don't need to serve any other PHP files besides index.php, use location /index.php here
    # instead, to prevent possible execution of user uploaded PHP code
    location ~ [^/]\.php(/|$) {

        # Define $fastcgi_script_name and $fastcgi_path_info
        fastcgi_split_path_info ^(.+?\.php)(/.*)$;

        # Immediately return 404 when script file does not exist
        if (!-f $document_root$fastcgi_script_name) {
            return 404;
        }

        # Mitigate https://httpoxy.org/ vulnerabilities
        fastcgi_param HTTP_PROXY "";

        # Define PHP backend location (find yours by grepping "listen ="
        # from your PHP config folder, e.g. grep -r "listen =" /etc/php/)
        fastcgi_pass unix:/run/php/php7.0-fpm.sock;

        # Set SCRIPT_FILENAME to execute
        fastcgi_param  SCRIPT_FILENAME    $document_root$fastcgi_script_name;

        # Include the default fastcgi parameters
        include fastcgi_params;

        # Overwrite REQUEST_URI (default is $request_uri) with $request_url we saved earlier
        fastcgi_param  REQUEST_URI        $request_url;
    }

}

结果是我不必在/sites/customerdemo.example.com/文件夹中执行git clone以外的任何操作,并运行composer installphp artisan migrate来添加一个新项目。

实际上,我已经开发了一个控制面板,我可以点击&#34;添加项目&#34;并指定项目详细信息和一个新的bitbucket repo,mysql用户和数据库将被创建,customerdemo服务器将被授予对此bitbucket repo的部署访问权限,并在此新repo中设置webhook,每次在customerdemo服务器上调用部署脚本有人承诺掌握这个repo,它将触发git clone或git pull和composer install以及数据库迁移。这就是我需要动态Nginx配置的原因。 ; - )

答案 7 :(得分:0)

选中此Nginx configuration,我相信它将为您提供帮助

$sql = "INSERT INTO ".$table_name." set local_url='".$local_url."',s3_url='".$s3_url."',meta_id='".$meta_id."',copied='".$copied." ";
$results = $wpdb->query($sql);