Deploy ZF2 site to shared host

2020-02-24 05:04发布

问题:

When you deploy a Zend Framework website to a shared host, you usually cannot change the DocumentRoot to point at the public/ folder of the website. As a result the URL to the website is now http://www.example.com/public/. This doesn't look very professional, so I'd like to remove it. Up to now I have used ZF1 and Rob Allen kindly provides a method for doing this on his blog http://akrabat.com/zend-framework/zend-framework-on-a-shared-host/ . I have tried to modify this for ZF2. He proposes placing an index.php file in the root with the line:

include 'public/index.php';

After doing this, http://www.example.com opens the index page OK but the CSS links are broken. Rob adds a controller plugin to reset the baseUrl to /public to deal with public facing CSS and image files etc. To do this in ZF2 I found an item from Matthew Weier O' Phinney http://zend-framework-community.634137.n4.nabble.com/Setting-the-base-url-in-ZF2-MVC-td3946284.html where he describes how to set the baseUrl. Based on his code I added this to modules/Application/Module.php

class Module {
    public function onBootstrap(MvcEvent $e) {
        $config          = $e->getApplication()->getServiceManager()->get('config');
        $router          = $e->getApplication()->getServiceManager()->get('router');        
        $router->setBaseUrl($config['base_url']);
    }
}

The base_url key is set in modules/Application/configs/module.config.php:

'base_url' => '/public'

I was able to dump the router object and confirm that the base_url was being set correctly at this stage. Unfortunately, now http://www.example.com no longer opens the index page and gives a 404 routing error.

Is anyone able to tell me what I am doing wrong or point me in the right direction for running a ZF2 site in a shared hosted environment?

回答1:

Are you using the skeleton app?

that seems a little over the top, surely it's lot simpler than that.

move everything from public to the root

change index.php

<?php
/**
 * This makes our life easier when dealing with paths. Everything is relative
 * to the application root now.
 */
//chdir(dirname(__DIR__));
chdir(__DIR__);

// Setup autoloading
require 'init_autoloader.php';

// Run the application!
Zend\Mvc\Application::init(require 'config/application.config.php')->run();

Simples.

If you are running an application like this you may want to block direct access to some of the Zend Framework folders using htaccess etc