When hosting Magento, using an Apache2 Virtual Host on Ubuntu for Magento 2 is the recommended way to serve your site on a dedicated domain or subdomain. A properly configured vHost allows you to keep site-specific settings isolated, apply Magento’s .htaccess
rules, and ensure clean URL handling without affecting other applications on the same server. In this guide, you’ll learn how to create and configure an Apache2 vHost for Magento 2 on Ubuntu, step by step.
Why an Apache2 Virtual Host Is Important for Magento 2
An Apache2 Virtual Host on Ubuntu for Magento 2 gives you flexibility and control. You can run multiple sites from the same server by assigning each one its own vHost configuration. For Magento, this means having a domain mapped to its pub
or root directory, enabling SEO-friendly URLs, and ensuring permissions are properly set for smooth operation.
Preparing Ubuntu and Apache2 for Magento 2 vHost
Before creating the vHost, make sure Apache2 is installed and the required modules are enabled:
sudo a2enmod rewrite sudo a2enmod headers sudo systemctl restart apache2
These modules are necessary for Magento 2’s URL rewrites and HTTP header management.
Creating the Apache2 Virtual Host File for Magento 2
Navigate to Apache’s site configuration directory and create a new file:
sudo nano /etc/apache2/sites-available/magento.conf
Add the following configuration (adjust ServerName
and DocumentRoot
to match your setup):
<VirtualHost *:80> ServerName magento.localhost DocumentRoot /var/www/html/magento <Directory /var/www/html/magento/> Options Indexes FollowSymLinks AllowOverride All Require all granted </Directory> ErrorLog ${APACHE_LOG_DIR}/magento_error.log CustomLog ${APACHE_LOG_DIR}/magento_access.log combined </VirtualHost>
The AllowOverride All directive is critical so Magento’s .htaccess
file can manage rewrites and other directives.
Enabling the Magento 2 vHost and Disabling Defaults
Once the configuration file is saved, enable the new vHost:
sudo a2ensite magento.conf sudo a2dissite 000-default.conf sudo systemctl reload apache2
This activates your Magento-specific vHost and disables Apache’s default site.
Setting Permissions for the Magento Directory
For Magento to run without file permission issues, ensure that the Magento user owns the web root:
sudo chown -R $USER:$USER /var/www/html/magento
Restarting Apache After vHost Changes
Restart Apache to apply the vHost configuration:
sudo systemctl restart apache2
Conclusion: A Clean and Scalable Apache2 vHost for Magento 2
Setting up an Apache2 Virtual Host on Ubuntu for Magento 2 is essential for both local development and production. It isolates your Magento configuration, enables SEO-friendly URLs, and ensures proper .htaccess
handling. With your vHost active, you’re ready to install Magento 2 or optimize an existing store for performance and scalability.
Leave a Reply