Tutoriel Complet : Installation et Configuration Magento

Magento alimente plus de 250,000 boutiques e-commerce dans le monde et génère plus de 155 milliards de dollars de GMV annuel. Ce guide détaillé vous accompagne dans l’installation complète de Magento, de la configuration serveur aux optimisations avancées.

🎯 Vue d’ensemble Magento

Magento Open Source vs Commerce

Magento Open Source (Gratuit) :

  • Core e-commerce functionality
  • Community support
  • Extensions marketplace
  • Self-hosted uniquement

Magento Commerce (22,000$/an) :

  • Fonctionnalités B2B avancées
  • Support officiel Adobe
  • Cloud hosting inclus
  • Page Builder, staging, reporting avancés

Architecture Technique

Frontend: PWA Studio (React), Luma theme (PHP)
Backend: PHP 8.1+, MySQL 8.0+, Elasticsearch
Cache: Redis, Varnish, Full Page Cache
Queue: RabbitMQ pour processing asynchrone

🖥️ Prérequis Serveur

1. Requirements Système

Serveur minimum :

OS: Ubuntu 20.04+ / CentOS 8+ / RHEL 8+
PHP: 8.1, 8.2 (PHP 8.3 supporté depuis Magento 2.4.6)
Database: MySQL 8.0+ ou MariaDB 10.4+
Web Server: Apache 2.4+ ou Nginx 1.18+
Memory: 4GB RAM minimum (8GB+ recommandé)
Storage: SSD, 25GB+ espace libre

Extensions PHP requises :

# Extensions PHP obligatoires
php8.1-common
php8.1-cli
php8.1-fpm
php8.1-mysql
php8.1-xml
php8.1-xmlrpc
php8.1-curl
php8.1-gd
php8.1-imagick
php8.1-dev
php8.1-imap
php8.1-mbstring
php8.1-opcache
php8.1-soap
php8.1-zip
php8.1-intl
php8.1-bcmath
php8.1-xsl

2. Configuration PHP Optimale

php.ini configuration :

# Basic settings
memory_limit = 4G
max_execution_time = 18000
max_input_vars = 10000
max_input_time = 1800
upload_max_filesize = 64M
post_max_size = 64M

# OPcache (critique pour performance)
opcache.enable = 1
opcache.enable_cli = 1
opcache.memory_consumption = 512
opcache.interned_strings_buffer = 16
opcache.max_accelerated_files = 100000
opcache.validate_timestamps = 0
opcache.revalidate_freq = 0
opcache.save_comments = 1

# Realpath cache (améliore I/O)
realpath_cache_size = 10M
realpath_cache_ttl = 7200

# Session settings
session.gc_maxlifetime = 7200

3. Configuration Base de Données

MySQL configuration :

-- my.cnf optimizations
[mysqld]
innodb_buffer_pool_size = 2G
innodb_log_file_size = 512M
innodb_flush_log_at_trx_commit = 2
innodb_flush_method = O_DIRECT
innodb_file_per_table = 1
innodb_open_files = 400

# Query cache
query_cache_type = 1
query_cache_size = 256M
query_cache_limit = 2M

# Connection settings
max_connections = 500
connect_timeout = 30
wait_timeout = 600
interactive_timeout = 600

# Buffer sizes
key_buffer_size = 256M
sort_buffer_size = 4M
read_buffer_size = 2M
read_rnd_buffer_size = 8M

📥 Installation Magento

1. Méthode Composer (Recommandée)

Installation via Composer :

# 1. Créer utilisateur magento
sudo adduser magento
sudo usermod -aG www-data magento

# 2. Installer Composer
curl -sS https://getcomposer.org/installer | php
sudo mv composer.phar /usr/local/bin/composer

# 3. Créer répertoire installation
sudo mkdir -p /var/www/magento2
sudo chown magento:www-data /var/www/magento2
cd /var/www/magento2

# 4. Installer Magento
composer create-project --repository-url=https://repo.magento.com/ magento/project-community-edition .

# 5. Authentification Magento
# Créer compte sur https://marketplace.magento.com/
# Utiliser Public Key comme username et Private Key comme password

2. Configuration Base de Données

Création base de données :

-- Connexion MySQL root
mysql -u root -p

-- Créer database et user
CREATE DATABASE magento2;
CREATE USER 'magento_user'@'localhost' IDENTIFIED BY 'secure_password_123';
GRANT ALL PRIVILEGES ON magento2.* TO 'magento_user'@'localhost';
FLUSH PRIVILEGES;
EXIT;

3. Installation CLI

Command line installation :

# Installation complète via CLI
php bin/magento setup:install \
--base-url=https://your-domain.com/ \
--db-host=localhost \
--db-name=magento2 \
--db-user=magento_user \
--db-password=secure_password_123 \
--admin-firstname=Admin \
--admin-lastname=User \
--admin-email=admin@your-domain.com \
--admin-user=admin \
--admin-password=SecureAdmin123! \
--language=en_US \
--currency=USD \
--timezone=America/Chicago \
--use-rewrites=1 \
--search-engine=elasticsearch7 \
--elasticsearch-host=localhost \
--elasticsearch-port=9200

4. Permissions et Security

File permissions :

# Définir owner et permissions
cd /var/www/magento2
sudo find var generated vendor pub/static pub/media app/etc -type f -exec chmod g+w {} +
sudo find var generated vendor pub/static pub/media app/etc -type d -exec chmod g+ws {} +
sudo chown -R magento:www-data .
sudo chmod u+x bin/magento

# Set proper permissions
sudo find . -type f -exec chmod 644 {} \;
sudo find . -type d -exec chmod 755 {} \;
sudo find ./var -type d -exec chmod 777 {} \;
sudo find ./pub/media -type d -exec chmod 777 {} \;
sudo find ./pub/static -type d -exec chmod 777 {} \;
sudo chmod 777 ./app/etc
sudo chmod 644 ./app/etc/*.xml

⚙️ Configuration Web Server

1. Apache Configuration

Virtual Host Apache :

<VirtualHost *:80>
    ServerName your-domain.com
    DocumentRoot /var/www/magento2/pub
    
    <Directory "/var/www/magento2/pub">
        AllowOverride All
        Require all granted
        Options -Indexes +FollowSymLinks
        
        # Enable rewrite engine
        RewriteEngine On
        
        # Security headers
        Header always set X-Frame-Options DENY
        Header always set X-Content-Type-Options nosniff
        Header always set X-XSS-Protection "1; mode=block"
        Header always set Strict-Transport-Security "max-age=31536000; includeSubDomains"
    </Directory>
    
    # Logs
    ErrorLog ${APACHE_LOG_DIR}/magento2_error.log
    CustomLog ${APACHE_LOG_DIR}/magento2_access.log combined
</VirtualHost>

<VirtualHost *:443>
    ServerName your-domain.com
    DocumentRoot /var/www/magento2/pub
    
    SSLEngine on
    SSLCertificateFile /path/to/certificate.crt
    SSLCertificateKeyFile /path/to/private.key
    
    # Same Directory config as above
    <Directory "/var/www/magento2/pub">
        AllowOverride All
        Require all granted
        Options -Indexes +FollowSymLinks
        RewriteEngine On
    </Directory>
</VirtualHost>

2. Nginx Configuration

Nginx server block :

server {
    listen 80;
    listen 443 ssl http2;
    server_name your-domain.com;
    
    # SSL configuration
    ssl_certificate /path/to/certificate.crt;
    ssl_certificate_key /path/to/private.key;
    ssl_protocols TLSv1.2 TLSv1.3;
    
    # Document root
    set $MAGE_ROOT /var/www/magento2;
    root $MAGE_ROOT/pub;
    
    index index.php;
    autoindex off;
    charset UTF-8;
    client_max_body_size 64m;
    
    # Security headers
    add_header X-Frame-Options DENY always;
    add_header X-Content-Type-Options nosniff always;
    add_header X-XSS-Protection "1; mode=block" always;
    
    # Main location
    location / {
        try_files $uri $uri/ /index.php$is_args$args;
    }
    
    # PHP handling
    location ~ \.php$ {
        try_files $uri =404;
        fastcgi_pass unix:/var/run/php/php8.1-fpm.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
        
        # Magento specific
        fastcgi_param MAGE_RUN_TYPE store;
        fastcgi_param MAGE_RUN_CODE default;
        
        # Cache control
        fastcgi_buffers 16 16k;
        fastcgi_buffer_size 32k;
        fastcgi_read_timeout 600s;
        fastcgi_connect_timeout 600s;
    }
    
    # Static files caching
    location ~* \.(ico|jpg|jpeg|png|gif|svg|js|css|swf|eot|ttf|otf|woff|woff2)$ {
        add_header Cache-Control "public";
        add_header X-Frame-Options "SAMEORIGIN";
        expires +1y;
        
        # Disable access logs for static files
        access_log off;
        
        if (!-f $request_filename) {
            rewrite ^/static/(version\d*/)?(.*)$ /static.php?resource=$2 last;
        }
    }
    
    # Media files
    location /media/ {
        try_files $uri $uri/ /get.php$is_args$args;
        
        location ~ ^/media/theme_customization/.*\.xml$ {
            deny all;
        }
        
        location ~* \.(ico|jpg|jpeg|png|gif|svg|js|css|swf|eot|ttf|otf|woff|woff2)$ {
            add_header Cache-Control "public";
            expires +1y;
            access_log off;
        }
    }
    
    # Admin location
    location ~* ^/(admin|admin_[a-zA-Z0-9]+)/ {
        try_files $uri $uri/ /index.php$is_args$args;
    }
    
    # Deny access to sensitive files
    location ~ ^/(app/|bin/|dev/|lib/|pub/errors|vendor/) {
        deny all;
    }
}

🔧 Configuration Post-Installation

1. Mode de Déploiement

Production mode setup :

# Passer en mode production
php bin/magento deploy:mode:set production

# Compiler DI et génération code
php bin/magento setup:di:compile

# Déploiement contenu statique
php bin/magento setup:static-content:deploy -f

# Reindex data
php bin/magento indexer:reindex

# Clear cache
php bin/magento cache:flush

2. Configuration Cache

Redis configuration :

# Installation Redis
sudo apt install redis-server

# Configuration Magento Redis
php bin/magento setup:config:set --cache-backend=redis --cache-backend-redis-server=127.0.0.1 --cache-backend-redis-db=0

# Session storage Redis
php bin/magento setup:config:set --session-save=redis --session-save-redis-host=127.0.0.1 --session-save-redis-log-level=3 --session-save-redis-db=1

# Page cache Redis
php bin/magento setup:config:set --page-cache=redis --page-cache-redis-server=127.0.0.1 --page-cache-redis-db=2

3. Elasticsearch Configuration

Elasticsearch setup :

# Installation Elasticsearch 7.x
wget -qO - https://artifacts.elastic.co/GPG-KEY-elasticsearch | sudo apt-key add -
echo "deb https://artifacts.elastic.co/packages/7.x/apt stable main" | sudo tee /etc/apt/sources.list.d/elastic-7.x.list
sudo apt update && sudo apt install elasticsearch

# Configuration
sudo nano /etc/elasticsearch/elasticsearch.yml
# Uncomment:
# network.host: localhost
# http.port: 9200

# Start service
sudo systemctl enable elasticsearch
sudo systemctl start elasticsearch

# Configure Magento
php bin/magento config:set catalog/search/engine elasticsearch7
php bin/magento config:set catalog/search/elasticsearch7_server_hostname localhost
php bin/magento config:set catalog/search/elasticsearch7_server_port 9200
php bin/magento indexer:reindex catalogsearch_fulltext

🎨 Configuration Thème et Store

1. Configuration Store

Multi-store setup :

# Créer website
php bin/magento store:website:create --code="eu" --name="Europe Store"

# Créer store
php bin/magento store:store:create --website-code="eu" --code="eu_en" --name="Europe English"

# Créer store view
php bin/magento store:view:create --website-code="eu" --store-code="eu_en" --code="eu_en_view" --name="Europe English View"

2. Thème Installation

Thème custom installation :

# Structure thème
mkdir -p app/design/frontend/YourCompany/your-theme
cd app/design/frontend/YourCompany/your-theme

# Créer registration.php
cat > registration.php << 'EOF'
<?php
use Magento\Framework\Component\ComponentRegistrar;

ComponentRegistrar::register(
    ComponentRegistrar::THEME,
    'frontend/YourCompany/your-theme',
    __DIR__
);
EOF

# Créer theme.xml
mkdir etc
cat > etc/theme.xml << 'EOF'
<?xml version="1.0"?>
<theme xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Config/etc/theme.xsd">
    <title>Your Custom Theme</title>
    <parent>Magento/luma</parent>
    <media>
        <preview_image>media/preview.jpg</preview_image>
    </media>
</theme>
EOF

# Activer thème
php bin/magento theme:uninstall --backup-code YourCompany/your-theme
php bin/magento setup:upgrade
php bin/magento cache:flush

3. Configuration Locale

Multi-langue setup :

# Installation packs langue
composer require magento/language-pack-fr_fr
composer require magento/language-pack-de_de
composer require magento/language-pack-es_es

# Déploiement langues
php bin/magento setup:static-content:deploy fr_FR de_DE es_ES
php bin/magento cache:flush

# Configuration via admin ou CLI
php bin/magento config:set general/locale/code fr_FR --scope=stores --scope-code=french_store

🚀 Optimisations Performance

1. Full Page Cache

Varnish configuration :

# Installation Varnish
sudo apt install varnish

# Export Varnish config depuis Magento
php bin/magento varnish:vcl:generate --export-version=6 > /etc/varnish/magento.vcl

# Configuration Varnish
sudo nano /etc/varnish/magento.vcl
# Ajuster backend settings:
backend default {
    .host = "127.0.0.1";
    .port = "8080";
    .connect_timeout = 600s;
    .first_byte_timeout = 600s;
    .between_bytes_timeout = 600s;
}

# Configuration Magento pour Varnish
php bin/magento config:set system/full_page_cache/caching_application 2
php bin/magento config:set system/full_page_cache/varnish/backend_host 127.0.0.1
php bin/magento config:set system/full_page_cache/varnish/backend_port 8080

2. Database Optimization

Index et optimisation :

-- Optimisations MySQL spécifiques Magento
ALTER TABLE catalog_product_entity_varchar ADD INDEX `idx_attribute_id_value` (`attribute_id`, `value`);
ALTER TABLE catalog_product_entity_int ADD INDEX `idx_attribute_id_value` (`attribute_id`, `value`);
ALTER TABLE catalog_product_entity_decimal ADD INDEX `idx_attribute_id_value` (`attribute_id`, `value`);

-- Cleanup automatique
CREATE EVENT magento_log_cleanup
ON SCHEDULE EVERY 1 WEEK
DO
BEGIN
    DELETE FROM log_url WHERE log_id < (SELECT log_id FROM (SELECT log_id FROM log_url ORDER BY log_id DESC LIMIT 10000,1) AS x);
    DELETE FROM log_visitor WHERE visitor_id < (SELECT visitor_id FROM (SELECT visitor_id FROM log_visitor ORDER BY visitor_id DESC LIMIT 10000,1) AS x);
    DELETE FROM report_event WHERE event_id < (SELECT event_id FROM (SELECT event_id FROM report_event ORDER BY event_id DESC LIMIT 10000,1) AS x);
END;

3. Static Content Optimization

Minification et bundling :

# Minification CSS/JS
php bin/magento config:set dev/css/minify_files 1
php bin/magento config:set dev/js/minify_files 1

# Bundling (production uniquement)
php bin/magento config:set dev/js/enable_js_bundling 1

# Image optimization
php bin/magento config:set dev/template/minify_html 1

# CDN configuration
php bin/magento config:set web/secure/base_static_url https://cdn.your-domain.com/static/
php bin/magento config:set web/secure/base_media_url https://cdn.your-domain.com/media/

📦 Extensions et Modules

1. Installation Extensions

Via Composer :

# Installer extension
composer require vendor/module-name

# Enable module
php bin/magento module:enable Vendor_ModuleName
php bin/magento setup:upgrade
php bin/magento setup:di:compile
php bin/magento cache:flush

Via Marketplace :

# Authentification
composer config http-basic.repo.magento.com <public_key> <private_key>

# Install depuis Marketplace
composer require magento/module-inventory-composer-installer
php bin/magento setup:upgrade

2. Modules Essentiels

Performance modules :

  • Amasty_PageSpeedOptimizer : Performance optimization
  • MGS_GDPR : GDPR compliance
  • Aheadworks_Layered_Navigation : Faceted search
  • Mageplaza_SEO : SEO optimization

Business modules :

  • Amasty_Promo : Promotional rules
  • Magento_InventoryManagement : MSI inventory
  • Klarna_Core : Payment gateway
  • Dotdigitalgroup_Email : Email marketing

🔒 Sécurité et Maintenance

1. Security Hardening

Basic security :

# Change admin path
php bin/magento config:set admin/url/custom_path custom_admin_path_123

# Enable 2FA
composer require magento/module-two-factor-auth
php bin/magento setup:upgrade

# Security headers via .htaccess
echo 'Header always set X-Frame-Options DENY
Header always set X-Content-Type-Options nosniff
Header always set X-XSS-Protection "1; mode=block"
Header always set Strict-Transport-Security "max-age=31536000; includeSubDomains"' >> pub/.htaccess

2. Backup Strategy

Automated backups :

#!/bin/bash
# backup-magento.sh

DATE=$(date +%Y%m%d_%H%M%S)
BACKUP_DIR="/backups/magento"
MAGENTO_DIR="/var/www/magento2"

# Create backup directory
mkdir -p $BACKUP_DIR/$DATE

# Database backup
mysqldump -u magento_user -p magento2 > $BACKUP_DIR/$DATE/database.sql

# Files backup (excluding cache)
tar --exclude='var/cache' --exclude='var/session' --exclude='var/log' \
    -czf $BACKUP_DIR/$DATE/magento-files.tar.gz -C $MAGENTO_DIR .

# Media backup
tar -czf $BACKUP_DIR/$DATE/media.tar.gz -C $MAGENTO_DIR/pub media

# Keep only last 7 days
find $BACKUP_DIR -type d -mtime +7 -exec rm -rf {} +

3. Monitoring et Maintenance

Health check script :

#!/bin/bash
# magento-health-check.sh

echo "=== Magento Health Check ==="

# Check disk space
df -h | grep -E "/$|/var"

# Check memory usage
free -h

# Check Magento cron
php bin/magento cron:run --group=default

# Check indexers status
php bin/magento indexer:status

# Check cache status
php bin/magento cache:status

# Check queue status (if using)
php bin/magento queue:consumers:list

# Database connection test
mysql -u magento_user -p -e "SELECT 1;" magento2

# Elasticsearch health
curl -X GET "localhost:9200/_cluster/health?pretty"

echo "=== Health Check Complete ==="

📊 Monitoring et Performance

1. Performance Monitoring

New Relic integration :

# Installation New Relic PHP agent
wget -O - https://download.newrelic.com/548C16BF.gpg | sudo apt-key add -
echo 'deb http://apt.newrelic.com/debian/ newrelic non-free' | sudo tee /etc/apt/sources.list.d/newrelic.list
sudo apt update && sudo apt install newrelic-php5

# Configuration
sudo newrelic-install install
sudo systemctl restart apache2  # ou nginx + php-fpm

# Magento New Relic module
composer require magento/module-new-relic
php bin/magento setup:upgrade

2. Log Management

Centralized logging :

# Logrotate configuration
sudo nano /etc/logrotate.d/magento

/var/www/magento2/var/log/*.log {
    daily
    missingok
    rotate 14
    compress
    delaycompress
    notifempty
    sharedscripts
    postrotate
        # Reload web server if needed
        /bin/kill -USR1 `cat /run/nginx.pid 2> /dev/null` 2> /dev/null || true
    endscript
}

✅ Checklist Post-Installation

Configuration Essentielle

  • SSL Certificate installé et configuré
  • Elasticsearch configuré et indexé
  • Redis configuré pour cache et sessions
  • Varnish configuré (production)
  • Permissions fichiers correctement définies
  • Cronjobs configurés et fonctionnels

Performance

  • OPcache activé et optimisé
  • Minification CSS/JS activée
  • Image optimization configurée
  • CDN configuré si applicable
  • Database optimisée et indexée
  • Load testing effectué

Sécurité

  • Admin URL personnalisée
  • 2FA activé pour admins
  • Security headers configurés
  • File permissions sécurisées
  • Firewall configuré
  • Backup strategy mise en place

Business

  • Payment gateways configurés et testés
  • Shipping methods configurés
  • Tax rules définies
  • Email templates personnalisés
  • SEO settings configurés
  • Analytics installé (GA, GTM)

🎯 Conclusion

L’installation de Magento est complexe mais cette complexité offre une flexibilité et des performances inégalées pour l’e-commerce enterprise. Les points critiques pour le succès :

  1. Infrastructure solide : Serveur correctement dimensionné et configuré
  2. Optimizations dès le début : Cache, OPcache, Redis, Elasticsearch
  3. Monitoring continu : Performance, sécurité, business metrics
  4. Maintenance préventive : Backups, updates, optimisation DB

Pro tip : Commencez par un setup simple en développement, testez intensivement, puis optimisez pour la production. Magento récompense la patience et l’expertise technique !

Votre installation Magento est maintenant prête pour conquérir le monde e-commerce ! 🚀