tuomas / anakkala.io

Serve Magento 2 with ngrok and Valet+

☕️ 1 min read

Configuring ngrok to serve Magento 2 with Valet+ is a fairly simple process.

If you have an existing secured site, start by unsecuring your site with valet unsecure. This will remove site specific nginx configuration file from ~/.valet/Nginx/.

To avoid problems down the road, set following values for fastcgi buffers:

$ echo 'fastcgi_buffers 16 256k;' >> ~/valet/Nginx/your-magento-site.test
$ echo 'fastcgi_buffer_size 256k;' >> ~/valet/Nginx/your-magento-site.test

Run valet serve. ngrok will output URLs for you, which you should set as Magento base URLs.

bin/magento config:set web/secure/base_url http://xxxxx.ngrok.io/
bin/magento config:set web/secure/base_link_url http://xxxxx.ngrok.io/
bin/magento config:set web/unsecure/base_url http://xxxxx.ngrok.io/
bin/magento config:set web/unsecure/base_link_url http://xxxxx.ngrok.io/

Valet will still add a .test as your TLD, which you can manually remove by adding following lines to Magentos pub/index.php:

$_SERVER['HTTP_HOST'] = str_replace('.test', '', $_SERVER['HTTP_HOST']);
$_SERVER['SERVER_NAME'] = str_replace('.test', '', $_SERVER['SERVER_NAME']);

Now you should be able to navigate and see your storefront with the URL provided by ngrok.

If accessing Magento admin results in redirect loop, ensure that the host Magento holds matches the host provided by ngrok. You can do this by inspecting the $host on vendor/magento/module-backend/App/Area/FrontNameResolver.php

Avoid sharing Magento with specific region, as $host might not then match the correct host provided by ngrok.

Sharing your development environment to a public URL can be a security concern, thus I would advise you restricting access to it.

$ sudo htpasswd -c /etc/apache2/.htpasswd user

Add following configurations to your site’s configuration file ~/.valet/Nginx/your-magento-site.test:

location / {
    auth_basic           "authenticate";
    auth_basic_user_file /etc/apache2/.htpasswd; 
}

Restart nginx with valet restart nginx.

If your Magento admin is still unaccesible, you can try disabling automatic redirect to base URL and ensure that admin area is using https.

$ bin/magento config:set web/url/redirect_to_base 0
$ bin/magento config:set web/secure/use_in_adminhtml 1