Magento – remove ‘pub/’ folder for URLs from command line

bin-magentoclimagento2

For increased security, we configured the DocumentRoot for our Magento application to be in the pub/ directory of the Magento installation, as described in the official documentation.

However, there is now a problem when executing commands on the command line – or when Magento's own cron is run: whenever a URL is generated for the front end context, e.g. via

$this->appEmulation->startEnvironmentEmulation(
    $store->getId(), \Magento\Framework\App\Area::AREA_FRONTEND, true
);

// …

$this->appEmulation->stopEnvironmentEmulation();

any generated front end URL – like for product images, will still contain the pub/ part of the URL.

The pub/index.php overrides the folder paths like this:

$params = $_SERVER;
$params[Bootstrap::INIT_PARAM_FILESYSTEM_DIR_PATHS] = [
    DirectoryList::PUB => [DirectoryList::URL_PATH => ''],
    DirectoryList::MEDIA => [DirectoryList::URL_PATH => 'media'],
    DirectoryList::STATIC_VIEW => [DirectoryList::URL_PATH => 'static'],
    DirectoryList::UPLOAD => [DirectoryList::URL_PATH => 'media/upload'],
];
$bootstrap = \Magento\Framework\App\Bootstrap::create(BP, $params);
/** @var \Magento\Framework\App\Http $app */
$app = $bootstrap->createApplication(\Magento\Framework\App\Http::class);
$bootstrap->run($app);

i.e., it simply removes the pub/ part from all these folder paths.

However, how can the same be done for the command line environment? (But only for the front end context.)

Magento version: 2.2.6

Best Answer

This is a more general problem of Magento, see magento/magento2#8868.

As a workaround we simply integrated the following RewriteRule in our pub/.htaccess:

RewriteRule ^pub/(.*) $1

Of course this does not solve the underlying issue of having wrong URLs being generated from the command line.

Related Topic