JavaScript pour débuter

Configurer Apache dossier par dossier : redirections, URL propres, sécurité et cache.

Introduction au .htaccess

Découvrez le fichier .htaccess et ses possibilités pour configurer Apache au niveau répertoire.

📋 Qu'est-ce que le .htaccess ?

Définition :

Le fichier .htaccess (HyperText Access) est un fichier de configuration décentralisée pour le serveur web Apache.

Il permet de définir des directives de configuration spécifiques à un répertoire et à ses sous-répertoires.

Contrairement à la configuration globale d'Apache, les modifications dans .htaccess sont prises en compte immédiatement.

✅ Avantages :
  • Configuration sans redémarrage du serveur
  • Contrôle granulaire par répertoire
  • Idéal pour l'hébergement mutualisé
  • Facile à déployer avec le code

Cas d'usage courants :

🔄 Redirections

Rediriger HTTP vers HTTPS, ancien vers nouveau domaine

🔗 URL Rewriting

URLs conviviales, masquer l'extension des fichiers

🛡️ Sécurité

Protection contre hotlinking, blocage d'IP

⚡ Performance

Compression, mise en cache, optimisation

Structure de base :

html

# Commentaire : Les lignes commençant par # sont des commentaires
# Structure générale d'une directive :
DirectiveName parametre1 parametre2
# Exemple concret :
RewriteEngine
 On
ErrorDocument
 404
                        /erreur404.html

Configuration de Base

Apprenez les directives fondamentales et la syntaxe du .htaccess.

📁 Création et Syntaxe de Base

Création du fichier :

html

# Créer le fichier .htaccess
touch .htaccess
# Ou avec un éditeur
nano .htaccess
vim .htaccess
# ⚠️ Important : Le nom commence par un point
# ⚠️ Pas d'extension de fichier

⚠️ Permissions importantes :

• Permissions recommandées : 644

• Lisible par le serveur web

• Non exécutable pour la sécurité

Règles de syntaxe :

html

# Règles de syntaxe importantes
# 1. Une directive par ligne
DirectiveName
 parametre
# 2. Sensible à la casse
RewriteEngine On
 # ✅
                                Correct

rewriteengine on

# ❌ Incorrect

# 3. Espaces comme séparateurs

ErrorDocument

404

/erreur.html

# 4. Échapper les caractères spéciaux

RewriteRule ^article/([0-9]+)$ /article.php?id=$1

Exemple de .htaccess de base :

html

# .htaccess - Configuration de base
# Créé le : 2024
# Description : Configuration Apache pour le répertoire courant

# ==========================================
# ACTIVATION DES MODULES
# ==========================================

# Activer le module de réécriture d'URL
RewriteEngine On

# Activer le suivi des liens symboliques
Options +FollowSymLinks

# ==========================================
# PAGES D'ERREUR PERSONNALISÉES
# ==========================================

# Page 404 - Page non trouvée
ErrorDocument 404 /erreurs/404.html

# Page 403 - Accès interdit
ErrorDocument 403 /erreurs/403.html

# Page 500 - Erreur serveur
ErrorDocument 500 /erreurs/500.html

# ==========================================
# INDEX DIRECTORY
# ==========================================

# Fichiers index par ordre de priorité
DirectoryIndex index.php index.html index.htm

# Interdire l'affichage du contenu des répertoires
Options -Indexes

# ==========================================
# ENCODAGE ET LANGUE
# ==========================================

# Définir l'encodage par défaut
AddDefaultCharset UTF-8

# Définir la langue par défaut
DefaultLanguage fr

# ==========================================
# TYPES MIME PERSONNALISÉS
# ==========================================

# Définir le type MIME pour les fichiers .webp
AddType image/webp .webp

# Définir le type MIME pour les fichiers .woff2
AddType font/woff2 .woff2

# ==========================================
# SÉCURITÉ DE BASE
# ==========================================

# Masquer la version d'Apache (si ServerTokens n'est pas configuré)
ServerSignature Off

# Empêcher l'accès aux fichiers sensibles
<Files ~ "^\.(htaccess|htpasswd|ini|log|sh|inc|bak)$">
    Order allow,deny
    Deny from all
</Files>

# Empêcher l'accès aux fichiers de sauvegarde
<FilesMatch "\.(bak|backup|save|old)$">
    Order allow,deny
    Deny from all
</FilesMatch>

Redirections

Maîtrisez les redirections HTTP : 301, 302, et leurs cas d'usage.

🔄 Types de Redirections

301 Redirection Permanente

• Transfert définitif de PageRank

• Recommandée pour le SEO

• Mise en cache par les navigateurs

html

Redirect 301

302 Redirection Temporaire

• Transfert temporaire

• PageRank conservé sur l'URL originale

• Non mise en cache par défaut

html

Redirect 302

307 Redirection Stricte

• Preserve la méthode HTTP

• POST reste POST

• Plus stricte que 302

html

Redirect 307

Avant / Après - Exemples de Redirections :

❌Avant : HTTP non sécurisé

html

http://monsite.com

• Données non chiffrées

• Mauvais pour le SEO

• Alerte navigateur

✅Après : HTTPS sécurisé

html

https://monsite.com

• Connexion sécurisée

• Meilleur classement SEO

• Confiance utilisateur

🔧 Exemples Pratiques de Redirections

html

# ==========================================
# REDIRECTIONS CLASSIQUES
# ==========================================

# 1. REDIRECTION HTTP VERS HTTPS (301 - Permanente)
# Redirige tout le trafic HTTP vers HTTPS
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

# 2. REDIRECTION WWW VERS NON-WWW (301 - Permanente)
# Redirige www.monsite.com vers monsite.com
RewriteEngine On
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ https://%1/$1 [R=301,L]

# 3. REDIRECTION NON-WWW VERS WWW (301 - Permanente)
# Redirige monsite.com vers www.monsite.com
RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTP_HOST} !^localhost$ [NC]
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}/$1 [R=301,L]

# ==========================================
# REDIRECTIONS DE PAGES SPÉCIFIQUES
# ==========================================

# 4. REDIRECTION D'UNE PAGE VERS UNE AUTRE (301)
# Ancienne page vers nouvelle page
Redirect 301 /ancienne-page.html /nouvelle-page.html
Redirect 301 /old-product /products/new-product

# 5. REDIRECTION D'UN RÉPERTOIRE COMPLET (301)
# Rediriger tout un dossier vers un autre
Redirect 301 /ancien-blog/ /blog/

# 6. REDIRECTION AVEC REWRITERULE (plus flexible)
# Rediriger toutes les pages d'une section
RewriteEngine On
RewriteRule ^old-section/(.*)$ /new-section/$1 [R=301,L]

# ==========================================
# REDIRECTIONS CONDITIONNELLES
# ==========================================

# 7. REDIRECTION SELON L'USER-AGENT
# Rediriger les mobiles vers version mobile
RewriteEngine On
RewriteCond %{HTTP_USER_AGENT} "android|blackberry|iphone|ipod|iemobile|opera mobile|palmos|webos|googlebot-mobile" [NC]
RewriteRule ^$ /mobile/ [L,R=302]

# 8. REDIRECTION SELON L'IP
# Rediriger certaines IPs vers une page spéciale
RewriteEngine On
RewriteCond %{REMOTE_ADDR} ^192\.168\.1\. [OR]
RewriteCond %{REMOTE_ADDR} ^10\.0\.0\.
RewriteRule ^(.*)$ /internal/$1 [L,R=302]

# ==========================================
# REDIRECTIONS POUR MAINTENANCE
# ==========================================

# 9. REDIRECTION TEMPORAIRE POUR MAINTENANCE (503)
# Rediriger vers page de maintenance sauf admin
RewriteEngine On
RewriteCond %{REMOTE_ADDR} !^123\.456\.789\.000$
RewriteCond %{REQUEST_URI} !/maintenance.html$
RewriteRule ^(.*)$ /maintenance.html [R=503,L]

# 10. REDIRECTION AVEC QUERY STRING
# Rediriger en préservant les paramètres GET
RewriteEngine On
RewriteRule ^old-search$ /search? [R=301,L,QSA]

# ==========================================
# REDIRECTIONS AVANCÉES
# ==========================================

# 11. REDIRECTION SELON LA LANGUE DU NAVIGATEUR
# Rediriger selon Accept-Language
RewriteEngine On
RewriteCond %{HTTP:Accept-Language} ^fr [NC]
RewriteRule ^$ /fr/ [L,R=302]
RewriteCond %{HTTP:Accept-Language} ^en [NC]
RewriteRule ^$ /en/ [L,R=302]
RewriteRule ^$ /en/ [L,R=302]

# 12. REDIRECTION TEMPORELLE
# Redirection active seulement pendant certaines heures
RewriteEngine On
RewriteCond %{TIME_HOUR} >22 [OR]
RewriteCond %{TIME_HOUR} <08
RewriteRule ^$ /ferme.html [L,R=302]

# ==========================================
# REDIRECTIONS POUR CHANGEMENT DE DOMAINE
# ==========================================

# 13. REDIRECTION COMPLÈTE VERS NOUVEAU DOMAINE
# Préserver toute la structure du site
RewriteEngine On
RewriteCond %{HTTP_HOST} ^ancien-domaine\.com$ [NC]
RewriteRule ^(.*)$ https://nouveau-domaine.com/$1 [R=301,L]

# 14. REDIRECTION AVEC MAPPING PERSONNALISÉ
# Rediriger selon une table de correspondance
RewriteEngine On
RewriteMap redirects txt:/path/to/redirects.txt
RewriteCond ${redirects:%{REQUEST_URI}} !=""
RewriteRule ^(.*)$ ${redirects:$1} [R=301,L]

# Contenu du fichier redirects.txt :
# /old-page1 /new-page1
# /old-page2 /new-page2
# /old-category/page /new-category/page

Réécriture d'URL (URL Rewriting)

Transformez vos URLs pour plus de lisibilité et un meilleur SEO.

🔗 Concepts et Syntaxe

Expressions régulières courantes :

html

# Motifs fréquents
^ : Début de chaîne
$ : Fin de chaîne
. : N'importe quel caractère
* : 0 ou plusieurs occurrences
+ : 1 ou plusieurs occurrences
? : 0 ou 1 occurrence
[0-9] : Chiffre
[a-z] : Lettre minuscule
([^/]+) : Capture jusqu'au slash

Flags (options) importantes :

html

# Flags essentiels
L : Last (arrête le traitement)
R : Redirect (redirection)
QSA : Query String Append
NC : No Case (insensible à la casse)
F : Forbidden
G : Gone
N : Next (continuer)
S : Skip

Avant / Après - URLs conviviales :

❌Avant : URLs techniques

html

                                        /article.php?id=123

html

                                        /product.php?category=5&id=42

html

                                        /user.php?action=profile&user=john

html

                                        /index.php?page=contact

• Difficiles à mémoriser • Mauvais pour le SEO • Peu esthétiques

✅Après : URLs conviviales

html

                                        /article/123

html

                                        /products/electronics/42

html

                                        /users/john/profile

html

                                        /contact

• Faciles à lire et mémoriser • Optimisées pour le SEO • Plus professionnelles

⚙️ Exemples de Réécriture d'URL

html

# ==========================================
# RÉÉCRITURE D'URL - EXEMPLES PRATIQUES
# ==========================================

RewriteEngine On

# ==========================================
# MASQUER LES EXTENSIONS DE FICHIER
# ==========================================

# 1. MASQUER L'EXTENSION .PHP
# /contact.php devient /contact
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.php [L]

# Empêcher l'accès direct aux .php (redirection)
RewriteCond %{THE_REQUEST} /([^.]+)\.php [NC]
RewriteRule ^ /%1 [NC,L,R=301]

# 2. MASQUER L'EXTENSION .HTML
# /about.html devient /about
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.html [L]

# ==========================================
# URLS POUR ARTICLES/BLOG
# ==========================================

# 3. ARTICLES PAR ID
# /article/123 → /article.php?id=123
RewriteRule ^article/([0-9]+)/?$ /article.php?id=$1 [L,QSA]

# 4. ARTICLES PAR SLUG
# /blog/mon-article → /blog.php?slug=mon-article
RewriteRule ^blog/([a-z0-9-]+)/?$ /blog.php?slug=$1 [L,QSA]

# 5. ARTICLES AVEC DATE
# /2024/03/15/mon-article → /article.php?year=2024&month=03&day=15&slug=mon-article
RewriteRule ^([0-9]{4})/([0-9]{2})/([0-9]{2})/([a-z0-9-]+)/?$ /article.php?year=$1&month=$2&day=$3&slug=$4 [L,QSA]

# ==========================================
# E-COMMERCE / PRODUITS
# ==========================================

# 6. PRODUITS PAR CATÉGORIE
# /products/electronics/42 → /product.php?category=electronics&id=42
RewriteRule ^products/([a-z0-9-]+)/([0-9]+)/?$ /product.php?category=$1&id=$2 [L,QSA]

# 7. RECHERCHE DE PRODUITS
# /search/laptops → /search.php?q=laptops
RewriteRule ^search/([a-z0-9-+%]+)/?$ /search.php?q=$1 [L,QSA]

# 8. PANIER D'ACHAT
# /cart/add/123 → /cart.php?action=add&id=123
RewriteRule ^cart/(add|remove|update)/([0-9]+)/?$ /cart.php?action=$1&id=$2 [L,QSA]

# ==========================================
# PROFILS UTILISATEURS
# ==========================================

# 9. PROFIL UTILISATEUR
# /user/john → /profile.php?username=john
RewriteRule ^user/([a-zA-Z0-9_-]+)/?$ /profile.php?username=$1 [L,QSA]

# 10. SECTIONS DU PROFIL
# /user/john/settings → /profile.php?username=john§ion=settings
RewriteRule ^user/([a-zA-Z0-9_-]+)/(settings|posts|friends)/?$ /profile.php?username=$1§ion=$2 [L,QSA]

# ==========================================
# PAGINATION
# ==========================================

# 11. PAGINATION SIMPLE
# /articles/page/2 → /articles.php?page=2
RewriteRule ^articles/page/([0-9]+)/?$ /articles.php?page=$1 [L,QSA]

# 12. PAGINATION PAR CATÉGORIE
# /category/tech/page/3 → /category.php?cat=tech&page=3
RewriteRule ^category/([a-z0-9-]+)/page/([0-9]+)/?$ /category.php?cat=$1&page=$2 [L,QSA]

# ==========================================
# API / SERVICES
# ==========================================

# 13. API REST-LIKE
# /api/users/123 → /api.php?resource=users&id=123
RewriteRule ^api/([a-z]+)/([0-9]+)/?$ /api.php?resource=$1&id=$2 [L,QSA]

# 14. API AVEC ACTION
# /api/users/123/update → /api.php?resource=users&id=123&action=update
RewriteRule ^api/([a-z]+)/([0-9]+)/(create|read|update|delete)/?$ /api.php?resource=$1&id=$2&action=$3 [L,QSA]

# ==========================================
# GESTION D'ÉVÉNEMENTS
# ==========================================

# 15. ÉVÉNEMENTS PAR DATE
# /events/2024/03/15 → /events.php?year=2024&month=03&day=15
RewriteRule ^events/([0-9]{4})/([0-9]{2})/([0-9]{2})/?$ /events.php?year=$1&month=$2&day=$3 [L,QSA]

# 16. ÉVÉNEMENT SPÉCIFIQUE
# /event/conference-web-2024 → /event.php?slug=conference-web-2024
RewriteRule ^event/([a-z0-9-]+)/?$ /event.php?slug=$1 [L,QSA]

# ==========================================
# LANGUES / INTERNATIONALISATION
# ==========================================

# 17. SUPPORT MULTI-LANGUES
# /fr/contact → /index.php?lang=fr&page=contact
# /en/about → /index.php?lang=en&page=about
RewriteRule ^(fr|en|es|de)/([a-z0-9-]+)/?$ /index.php?lang=$1&page=$2 [L,QSA]

# ==========================================
# RÈGLES AVANCÉES AVEC CONDITIONS
# ==========================================

# 18. RÉÉCRITURE CONDITIONNELLE (fichier n'existe pas)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([a-z0-9-]+)/?$ /page.php?slug=$1 [L,QSA]

# 19. EXCLUSION DE RÉPERTOIRES
# Exclure admin/ et assets/ de la réécriture
RewriteCond %{REQUEST_URI} !^/(admin|assets|images|css|js)/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([a-z0-9-]+)/?$ /content.php?page=$1 [L,QSA]

# 20. RÉÉCRITURE AVEC QUERY STRING EXISTANTE
# Préserver les paramètres GET existants avec QSA
RewriteRule ^download/([0-9]+)/?$ /download.php?file_id=$1 [L,QSA]

# ==========================================
# CMS / ROUTING AVANCÉ
# ==========================================

# 21. ROUTING POUR CMS
# Tout ce qui n'est pas un fichier → index.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !^/(admin|assets|uploads)/
RewriteRule ^(.*)$ /index.php?route=$1 [L,QSA]

# 22. SOUS-DOMAINES VERS RÉPERTOIRES
# Si utilisé dans httpd.conf ou vhost :
# RewriteCond %{HTTP_HOST} ^([^.]+)\.monsite\.com$ [NC]
# RewriteRule ^(.*)$ /sites/%1/$1 [L]

Sécurité avec .htaccess

Protégez votre site web avec des directives de sécurité efficaces.

🛡️ Protection et Sécurisation

Vulnérabilités courantes :

🚫 Directory Listing

Exposition du contenu des répertoires

💾 Fichiers sensibles

Accès aux fichiers de configuration

🔗 Hotlinking

Vol de bande passante par liens directs

🌐 IPs malveillantes

Attaques par adresses IP spécifiques

Avant / Après - Sécurité :

❌Avant : Site vulnérable

• Fichiers .htaccess lisibles

• Répertoires exposés publiquement

• Pas de protection hotlinking

• Informations serveur exposées

✅Après : Site sécurisé

• Fichiers sensibles protégés

• Directory listing désactivé

• Protection contre hotlinking

• En-têtes de sécurité ajoutés

🔒 Configuration Sécurisée

html

# ==========================================
# SÉCURITÉ .HTACCESS - CONFIGURATION COMPLÈTE
# ==========================================

# ==========================================
# PROTECTION DES FICHIERS SENSIBLES
# ==========================================

# 1. PROTÉGER LES FICHIERS DE CONFIGURATION
# Empêcher l'accès aux fichiers sensibles
<FilesMatch "^\.ht">
    Require all denied
</FilesMatch>

# 2. PROTÉGER LES FICHIERS SPÉCIFIQUES
<Files ~ "\.(htaccess|htpasswd|ini|phps|fla|psd|log|sh|sql|conf|bak|old|tmp)$">
    Order allow,deny
    Deny from all
</Files>

# 3. PROTÉGER LES FICHIERS DE SAUVEGARDE
<FilesMatch "\.(bak|backup|save|old|orig|original|tmp|temp|cache)$">
    Order allow,deny
    Deny from all
</FilesMatch>

# 4. PROTÉGER LE FICHIER WP-CONFIG (WordPress)
<Files wp-config.php>
    Order allow,deny
    Deny from all
</Files>

# ==========================================
# DÉSACTIVER L'AFFICHAGE DES RÉPERTOIRES
# ==========================================

# 5. EMPÊCHER LE DIRECTORY LISTING
Options -Indexes

# Alternative avec mod_autoindex
<IfModule mod_autoindex.c>
    Options -Indexes
</IfModule>

# ==========================================
# MASQUER LES INFORMATIONS DU SERVEUR
# ==========================================

# 6. MASQUER LA SIGNATURE DU SERVEUR
ServerSignature Off

# 7. DÉSACTIVER LA VERSION D'APACHE (si possible)
# Note: Nécessite ServerTokens Prod dans httpd.conf
<IfModule mod_headers.c>
    Header unset Server
    Header unset X-Powered-By
</IfModule>

# ==========================================
# PROTECTION CONTRE LES ATTAQUES
# ==========================================

# 8. BLOQUER LES USER-AGENTS MALVEILLANTS
RewriteEngine On
RewriteCond %{HTTP_USER_AGENT} (libwww-perl|wget|python|nikto|curl|scan|java|winhttp|clshttp|loader) [NC,OR]
RewriteCond %{HTTP_USER_AGENT} (<|>|'|%0A|%0D|%27|%3C|%3E|%00) [NC,OR]
RewriteCond %{HTTP_USER_AGENT} (;|<|>|'|"|\)|\(|%0A|%0D|%22|%27|%28|%3C|%3E|%00).*(libwww-perl|wget|python|nikto|curl|scan|java|winhttp|HTTrack|clshttp|archiver|loader|email|harvest|extract|grab|miner) [NC]
RewriteRule .* - [F]

# 9. BLOQUER LES REQUÊTES SUSPECTES
RewriteCond %{QUERY_STRING} (;|<|>|'|"|\)|%0A|%0D|%22|%27|%3C|%3E|%00).*(/\*|union|select|insert|cast|set|declare|drop|update|md5|benchmark) [NC]
RewriteRule .* - [F]

# 10. PROTECTION CONTRE LES INJECTIONS SQL
RewriteCond %{QUERY_STRING} ([a-z0-9]{2000}) [NC,OR]
RewriteCond %{QUERY_STRING} (/|%2f)(:|%3a)(/|%2f) [NC,OR]
RewriteCond %{QUERY_STRING} (order(\s|%20)by(\s|%20)1--) [NC,OR]
RewriteCond %{QUERY_STRING} (/|%2f)(\*|%2a)(\*|%2a)(/|%2f) [NC,OR]
RewriteCond %{QUERY_STRING} (`|<|>|\^|\|\\|0x00|%00|%0d%0a) [NC]
RewriteRule .* - [F]

# ==========================================
# BLOCAGE D'ADRESSES IP
# ==========================================

# 11. BLOQUER DES IPS SPÉCIFIQUES
<RequireAll>
    Require all granted
    Require not ip 192.168.1.100
    Require not ip 10.0.0.0/8
    Require not ip 203.0.113.0/24
</RequireAll>

# Alternative avec mod_rewrite
RewriteEngine On
RewriteCond %{REMOTE_ADDR} ^192\.168\.1\.100$
RewriteRule .* - [F]

# 12. AUTORISER SEULEMENT CERTAINES IPS (ADMIN)
<Files "admin.php">
    <RequireAll>
        Require ip 192.168.1.0/24
        Require ip 203.0.113.50
    </RequireAll>
</Files>

# ==========================================
# PROTECTION CONTRE LE HOTLINKING
# ==========================================

# 13. EMPÊCHER LE HOTLINKING D'IMAGES
RewriteEngine On
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^https?://(www\.)?monsite\.com [NC]
RewriteCond %{HTTP_REFERER} !^https?://(www\.)?google\.com [NC]
RewriteCond %{HTTP_REFERER} !^https?://(www\.)?bing\.com [NC]
RewriteRule \.(jpg|jpeg|png|gif|bmp|webp)$ /images/hotlink-protection.jpg [R,L]

# 14. BLOQUER LE HOTLINKING AVEC MESSAGE D'ERREUR
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^https?://(www\.)?monsite\.com [NC]
RewriteRule \.(jpg|jpeg|png|gif|pdf|zip)$ - [F]

# ==========================================
# AUTHENTIFICATION PAR MOT DE PASSE
# ==========================================

# 15. PROTÉGER UN RÉPERTOIRE PAR MOT DE PASSE
AuthType Basic
AuthName "Zone Protégée - Accès Restreint"
AuthUserFile /path/to/.htpasswd
Require valid-user

# Pour créer le fichier .htpasswd :
# htpasswd -c .htpasswd username

# 16. PROTÉGER UN FICHIER SPÉCIFIQUE
<Files "admin.php">
    AuthType Basic
    AuthName "Administration"
    AuthUserFile /path/to/.htpasswd
    Require valid-user
</Files>

# ==========================================
# EN-TÊTES DE SÉCURITÉ
# ==========================================

# 17. AJOUTER DES EN-TÊTES DE SÉCURITÉ
<IfModule mod_headers.c>
    # Protection XSS
    Header set X-XSS-Protection "1; mode=block"

    # Empêcher le sniffing MIME
    Header set X-Content-Type-Options "nosniff"

    # Protection contre le clickjacking
    Header set X-Frame-Options "SAMEORIGIN"

    # Forcer HTTPS (HSTS)
    Header set Strict-Transport-Security "max-age=31536000; includeSubDomains"

    # Politique de référent
    Header set Referrer-Policy "strict-origin-when-cross-origin"

    # CSP (Content Security Policy) basique
    Header set Content-Security-Policy "default-src 'self'; img-src 'self' data: https:; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'"
</IfModule>

# ==========================================
# LIMITATION DES MÉTHODES HTTP
# ==========================================

# 18. AUTORISER SEULEMENT GET, POST, HEAD
<LimitExcept GET POST HEAD>
    Require all denied
</LimitExcept>

# 19. BLOQUER CERTAINES MÉTHODES
RewriteEngine On
RewriteCond %{REQUEST_METHOD} ^(TRACE|DELETE|TRACK) [NC]
RewriteRule .* - [F]

# ==========================================
# PROTECTION DES UPLOADS
# ==========================================

# 20. EMPÊCHER L'EXÉCUTION DE SCRIPTS DANS UPLOADS
<Directory "/uploads">
    <FilesMatch "\.(php|phtml|php3|php4|php5|pl|py|jsp|asp|aspx|sh|cgi)$">
        Order allow,deny
        Deny from all
    </FilesMatch>
</Directory>

# 21. LIMITER LA TAILLE DES UPLOADS (si possible)
LimitRequestBody 10485760  # 10MB max

# ==========================================
# SURVEILLANCE ET LOGGING
# ==========================================

# 22. LOGUER LES TENTATIVES D'ACCÈS SUSPECTS
RewriteEngine On
RewriteCond %{HTTP_USER_AGENT} (bot|crawler|spider|scraper) [NC]
RewriteRule .* - [E=suspect:1]
CustomLog /var/log/apache2/suspect.log combined env=suspect

# 23. REDIRIGER LES 404 SUSPECTS
RewriteCond %{REQUEST_URI} (wp-admin|wp-login|xmlrpc|phpmyadmin)
RewriteRule .* - [F,L]

Performance et Optimisation

Améliorez les performances de votre site avec la compression et la mise en cache.

⚡ Optimisations de Performance

html

# ==========================================
# PERFORMANCE ET OPTIMISATION
# ==========================================

# ==========================================
# COMPRESSION GZIP/DEFLATE
# ==========================================

# 1. COMPRESSION GZIP (mod_deflate)
<IfModule mod_deflate.c>
    # Activer la compression pour ces types MIME
    AddOutputFilterByType DEFLATE text/plain
    AddOutputFilterByType DEFLATE text/html
    AddOutputFilterByType DEFLATE text/xml
    AddOutputFilterByType DEFLATE text/css
    AddOutputFilterByType DEFLATE text/javascript
    AddOutputFilterByType DEFLATE application/xml
    AddOutputFilterByType DEFLATE application/xhtml+xml
    AddOutputFilterByType DEFLATE application/rss+xml
    AddOutputFilterByType DEFLATE application/atom_xml
    AddOutputFilterByType DEFLATE application/javascript
    AddOutputFilterByType DEFLATE application/x-javascript
    AddOutputFilterByType DEFLATE application/json
    AddOutputFilterByType DEFLATE application/ld+json

    # Exclure les fichiers déjà compressés
    SetEnvIfNoCase Request_URI \
        \.(?:gif|jpe?g|png|swf|woff|woff2|zip|gz|rar|bz2|sit|pdf|exe|dmg)$ no-gzip dont-vary

    # Exclure les vieux navigateurs
    BrowserMatch ^Mozilla/4 gzip-only-text/html
    BrowserMatch ^Mozilla/4\.0[678] no-gzip
    BrowserMatch \bMSIE !no-gzip !gzip-only-text/html

    # S'assurer que les proxies ne livrent pas le mauvais contenu
    Header append Vary User-Agent
</IfModule>

# 2. COMPRESSION ALTERNATIVE (mod_gzip - Apache 1.x)
<IfModule mod_gzip.c>
    mod_gzip_on Yes
    mod_gzip_dechunk Yes
    mod_gzip_item_include file \.(html?|txt|css|js|php|pl)$
    mod_gzip_item_include mime ^text/.*
    mod_gzip_item_include mime ^application/x-javascript.*
    mod_gzip_item_exclude mime ^image/.*
    mod_gzip_item_exclude rspheader ^Content-Encoding:.*gzip.*
</IfModule>

# ==========================================
# MISE EN CACHE (Cache Control)
# ==========================================

# 3. EXPIRATION DES FICHIERS STATIQUES
<IfModule mod_expires.c>
    ExpiresActive On

    # Images (1 an)
    ExpiresByType image/jpg "access plus 1 year"
    ExpiresByType image/jpeg "access plus 1 year"
    ExpiresByType image/gif "access plus 1 year"
    ExpiresByType image/png "access plus 1 year"
    ExpiresByType image/webp "access plus 1 year"
    ExpiresByType image/svg+xml "access plus 1 year"
    ExpiresByType image/x-icon "access plus 1 year"
    ExpiresByType image/vnd.microsoft.icon "access plus 1 year"

    # Vidéo et audio (1 mois)
    ExpiresByType video/webm "access plus 1 month"
    ExpiresByType video/mp4 "access plus 1 month"
    ExpiresByType video/avi "access plus 1 month"
    ExpiresByType audio/mp3 "access plus 1 month"
    ExpiresByType audio/wav "access plus 1 month"

    # Fonts (1 an)
    ExpiresByType font/woff2 "access plus 1 year"
    ExpiresByType font/woff "access plus 1 year"
    ExpiresByType font/ttf "access plus 1 year"
    ExpiresByType font/eot "access plus 1 year"
    ExpiresByType application/font-woff "access plus 1 year"
    ExpiresByType application/font-woff2 "access plus 1 year"

    # CSS et JavaScript (1 semaine)
    ExpiresByType text/css "access plus 1 week"
    ExpiresByType application/javascript "access plus 1 week"
    ExpiresByType application/x-javascript "access plus 1 week"

    # HTML (1 heure)
    ExpiresByType text/html "access plus 1 hour"

    # XML et JSON (1 jour)
    ExpiresByType application/xml "access plus 1 day"
    ExpiresByType text/xml "access plus 1 day"
    ExpiresByType application/json "access plus 1 day"

    # Manifeste (1 semaine)
    ExpiresByType application/manifest+json "access plus 1 week"
    ExpiresByType text/cache-manifest "access plus 1 week"

    # Archives (1 mois)
    ExpiresByType application/zip "access plus 1 month"
    ExpiresByType application/x-rar-compressed "access plus 1 month"
    ExpiresByType application/pdf "access plus 1 month"

    # Par défaut (1 jour)
    ExpiresDefault "access plus 1 day"
</IfModule>

# 4. HEADERS DE CACHE AVEC mod_headers
<IfModule mod_headers.c>
    # Images - Cache 1 an
    <FilesMatch "\.(jpg|jpeg|png|gif|webp|ico|svg)$">
        Header set Cache-Control "max-age=31536000, public"
        Header set Expires "Thu, 31 Dec 2025 20:00:00 GMT"
        Header unset ETag
        Header unset Last-Modified
    </FilesMatch>

    # CSS et JS - Cache 1 semaine
    <FilesMatch "\.(css|js)$">
        Header set Cache-Control "max-age=604800, public"
        Header set Expires "Thu, 31 Dec 2024 20:00:00 GMT"
    </FilesMatch>

    # Fonts - Cache 1 an
    <FilesMatch "\.(woff2|woff|ttf|eot)$">
        Header set Cache-Control "max-age=31536000, public"
        Header set Expires "Thu, 31 Dec 2025 20:00:00 GMT"
    </FilesMatch>

    # HTML - Pas de cache
    <FilesMatch "\.(html|htm|php)$">
        Header set Cache-Control "no-cache, no-store, must-revalidate"
        Header set Pragma "no-cache"
        Header set Expires "0"
    </FilesMatch>
</IfModule>

# ==========================================
# OPTIMISATION DES IMAGES
# ==========================================

# 5. SERVIR LES FORMATS MODERNES D'IMAGES
<IfModule mod_rewrite.c>
    RewriteEngine On

    # WebP pour les navigateurs compatibles
    RewriteCond %{HTTP_ACCEPT} image/webp
    RewriteCond %{REQUEST_FILENAME} \.(png|jpg|jpeg)$
    RewriteCond %{REQUEST_FILENAME}.webp -f
    RewriteRule ^(.*)$ $1.webp [L,T=image/webp]

    # AVIF pour les navigateurs compatibles (futur)
    RewriteCond %{HTTP_ACCEPT} image/avif
    RewriteCond %{REQUEST_FILENAME} \.(png|jpg|jpeg)$
    RewriteCond %{REQUEST_FILENAME}.avif -f
    RewriteRule ^(.*)$ $1.avif [L,T=image/avif]
</IfModule>

# 6. OPTIMISATION DES IMAGES SVG
<IfModule mod_headers.c>
    <FilesMatch "\.svg$">
        Header set Cache-Control "max-age=31536000, public"
        Header set Content-Type "image/svg+xml"
        Header set Vary "Accept-Encoding"
    </FilesMatch>
</IfModule>

# ==========================================
# PRÉCHARGEMENT DES RESSOURCES
# ==========================================

# 7. PRÉCHARGEMENT DNS
<IfModule mod_headers.c>
    Header add Link "</fonts.googleapis.com>; rel=dns-prefetch"
    Header add Link "<https://cdnjs.cloudflare.com>; rel=dns-prefetch"
    Header add Link "<https://cdn.jsdelivr.net>; rel=dns-prefetch"
</IfModule>

# 8. PRÉCHARGEMENT DE RESSOURCES CRITIQUES
<IfModule mod_headers.c>
    # Précharger les fonts importantes
    <FilesMatch "\.html$">
        Header add Link "</fonts/main.woff2>; rel=preload; as=font; type=font/woff2; crossorigin"
        Header add Link "</css/critical.css>; rel=preload; as=style"
        Header add Link "</js/critical.js>; rel=preload; as=script"
    </FilesMatch>
</IfModule>

# ==========================================
# OPTIMISATION DU SERVEUR
# ==========================================

# 9. DÉSACTIVER LES ETAGS (pour plusieurs serveurs)
<IfModule mod_headers.c>
    Header unset ETag
</IfModule>
FileETag None

# 10. OPTIMISER LA LIVRAISON DES FICHIERS
<IfModule mod_mime.c>
    # Compression des fonts
    AddType application/font-woff .woff
    AddType application/font-woff2 .woff2
    AddType application/vnd.ms-fontobject .eot
    AddType application/x-font-ttf .ttf
</IfModule>

# ==========================================
# RÉDUCTION DES REQUÊTES HTTP
# ==========================================

# 11. COMBINAISON DE FICHIERS CSS (exemple avec mod_rewrite)
<IfModule mod_rewrite.c>
    # Rediriger vers un fichier CSS combiné
    RewriteRule ^css/combined\.css$ /combine.php?type=css [L]
    RewriteRule ^js/combined\.js$ /combine.php?type=js [L]
</IfModule>

# ==========================================
# HEADERS DE PERFORMANCE
# ==========================================

# 12. HEADERS DE PERFORMANCE SUPPLÉMENTAIRES
<IfModule mod_headers.c>
    # Activer HTTP/2 Server Push (si supporté)
    Header add Link "</css/style.css>; rel=preload; as=style"
    Header add Link "</js/app.js>; rel=preload; as=script"

    # Optimiser le cache des redirections
    <FilesMatch "\.(html|htm|php)$">
        Header merge Cache-Control "no-transform"
    </FilesMatch>

    # Accélération avec mod_pagespeed (si installé)
    ModPagespeed on
    ModPagespeedEnableFilters rewrite_css,rewrite_javascript,rewrite_images
    ModPagespeedEnableFilters collapse_whitespace,remove_comments
</IfModule>

# ==========================================
# OPTIMISATION MOBILE
# ==========================================

# 13. OPTIMISATION POUR MOBILE
<IfModule mod_headers.c>
    # Viewport et optimisations mobile
    <FilesMatch "\.(html|htm|php)$">
        Header append Vary User-Agent
        Header set X-UA-Compatible "IE=edge"
    </FilesMatch>
</IfModule>

# 14. ADAPTIVE IMAGES (exemple basique)
<IfModule mod_rewrite.c>
    RewriteCond %{HTTP_USER_AGENT} "android|blackberry|iphone|ipod|mobile|smartphone|tablet" [NC]
    RewriteCond %{REQUEST_FILENAME} \.(jpg|jpeg|png)$
    RewriteCond %{REQUEST_FILENAME} !mobile
    RewriteRule ^(.*)$ mobile/$1 [L]
</IfModule>

Exemples Pratiques Complets

Fichiers .htaccess prêts à l'emploi pour différents types de sites web.

🌐 Site Vitrine / Corporate

html

# ==========================================
# SITE VITRINE / CORPORATE - .htaccess
# ==========================================

# Activation des modules nécessaires
RewriteEngine On
Options +FollowSymLinks -Indexes

# ==========================================
# REDIRECTIONS DE BASE
# ==========================================

# Force HTTPS
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

# Force www (ou non-www selon préférence)
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTP_HOST} !^localhost [NC]
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}/$1 [R=301,L]

# ==========================================
# STRUCTURE D'URL CONVIVIALE
# ==========================================

# Pages principales sans extension
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([a-z0-9-]+)/?$ /$1.php [L]

# Sous-pages (ex: services/web-design)
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([a-z0-9-]+)/([a-z0-9-]+)/?$ /$1/$2.php [L]

# Blog/actualités avec date
RewriteRule ^actualites/([0-9]{4})/([0-9]{2})/([a-z0-9-]+)/?$ /actualites.php?year=$1&month=$2&slug=$3 [L,QSA]

# Contact et formulaires
RewriteRule ^contact/(merci|erreur)/?$ /contact.php?status=$1 [L,QSA]

# ==========================================
# SÉCURITÉ
# ==========================================

# Protection fichiers sensibles
<FilesMatch "^\.">
    Require all denied
</FilesMatch>

# Protection uploads
<Directory "/uploads">
    <FilesMatch "\.(php|phtml|php3|php4|php5)$">
        Order allow,deny
        Deny from all
    </FilesMatch>
</Directory>

# En-têtes de sécurité
<IfModule mod_headers.c>
    Header set X-Content-Type-Options "nosniff"
    Header set X-Frame-Options "SAMEORIGIN"
    Header set X-XSS-Protection "1; mode=block"
    Header set Referrer-Policy "strict-origin-when-cross-origin"
</IfModule>

# ==========================================
# PERFORMANCE
# ==========================================

# Compression
<IfModule mod_deflate.c>
    AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css text/javascript application/javascript application/json
</IfModule>

# Cache
<IfModule mod_expires.c>
    ExpiresActive On
    ExpiresByType image/jpg "access plus 1 year"
    ExpiresByType image/png "access plus 1 year"
    ExpiresByType text/css "access plus 1 month"
    ExpiresByType application/pdf "access plus 1 month"
    ExpiresByType application/javascript "access plus 1 month"
    ExpiresByType text/html "access plus 1 hour"
</IfModule>

# ==========================================
# PAGES D'ERREUR
# ==========================================

ErrorDocument 404 /404.php
ErrorDocument 403 /403.php
ErrorDocument 500 /500.php

# ==========================================
# REDIRECTIONS SPÉCIFIQUES
# ==========================================

# Anciennes URLs vers nouvelles
Redirect 301 /old-page.html /nouvelle-page
Redirect 301 /services.html /services
Redirect 301 /contact.html /contact

🛒 Site E-commerce

html

# ==========================================
# E-COMMERCE - .htaccess AVANCÉ
# ==========================================

RewriteEngine On
Options +FollowSymLinks -Indexes

# ==========================================
# SÉCURITÉ E-COMMERCE RENFORCÉE
# ==========================================

# HTTPS obligatoire
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

# Protection admin
<Files "admin.php">
    AuthType Basic
    AuthName "Administration E-commerce"
    AuthUserFile /path/to/.htpasswd
    Require valid-user

    # + Restriction IP
    <RequireAll>
        Require valid-user
        Require ip 192.168.1.0/24
    </RequireAll>
</Files>

# Protection base de données
<FilesMatch "(config|database|\.env)">
    Require all denied
</FilesMatch>

# ==========================================
# STRUCTURE PRODUITS E-COMMERCE
# ==========================================

# Catégories : /category/electronics
RewriteRule ^category/([a-z0-9-]+)/?$ /category.php?slug=$1 [L,QSA]

# Produits : /product/laptop-dell-xps-13
RewriteRule ^product/([a-z0-9-]+)/?$ /product.php?slug=$1 [L,QSA]

# Produits par catégorie : /electronics/laptop-dell-xps-13
RewriteRule ^([a-z0-9-]+)/([a-z0-9-]+)/?$ /product.php?category=$1&product=$2 [L,QSA]

# Recherche : /search/laptops
RewriteRule ^search/([a-zA-Z0-9\+\-\s%]+)/?$ /search.php?q=$1 [L,QSA]

# Panier et commandes
RewriteRule ^cart/?$ /cart.php [L]
RewriteRule ^cart/(add|remove|update)/([0-9]+)/?$ /cart.php?action=$1&id=$2 [L,QSA]
RewriteRule ^checkout/?$ /checkout.php [L]
RewriteRule ^checkout/(step-[1-4])/?$ /checkout.php?step=$1 [L,QSA]

# Compte utilisateur
RewriteRule ^account/?$ /account.php [L]
RewriteRule ^account/(orders|profile|addresses|wishlist)/?$ /account.php?section=$1 [L,QSA]
RewriteRule ^account/order/([0-9]+)/?$ /account.php?section=orders&id=$1 [L,QSA]

# ==========================================
# OPTIMISATION SEO E-COMMERCE
# ==========================================

# URLs canoniques pour éviter le contenu dupliqué
RewriteCond %{QUERY_STRING} ^$
RewriteCond %{REQUEST_URI} !/$
RewriteRule ^(.+)$ /$1/ [R=301,L]

# Pagination SEO-friendly
RewriteRule ^([a-z0-9-]+)/page/([0-9]+)/?$ /category.php?slug=$1&page=$2 [L,QSA]

# Filtres produits
RewriteRule ^([a-z0-9-]+)/filter/(price|brand|rating)/([a-z0-9-]+)/?$ /category.php?slug=$1&filter=$2&value=$3 [L,QSA]

# ==========================================
# PERFORMANCE E-COMMERCE
# ==========================================

# Cache agressif pour les images produits
<IfModule mod_expires.c>
    <FilesMatch "\.(jpg|jpeg|png|webp|gif)$">
        ExpiresActive On
        ExpiresByType image/jpg "access plus 1 year"
        ExpiresByType image/png "access plus 1 year"
        ExpiresByType image/webp "access plus 1 year"
    </FilesMatch>
</IfModule>

# WebP pour images produits
<IfModule mod_rewrite.c>
    RewriteCond %{HTTP_ACCEPT} image/webp
    RewriteCond %{REQUEST_FILENAME} \.(jpg|jpeg|png)$
    RewriteCond %{REQUEST_FILENAME}.webp -f
    RewriteRule ^(.*)$ $1.webp [L,T=image/webp]
</IfModule>

# Compression pour JSON API
<IfModule mod_deflate.c>
    AddOutputFilterByType DEFLATE application/json
    AddOutputFilterByType DEFLATE application/xml
</IfModule>

# ==========================================
# API E-COMMERCE
# ==========================================

# API REST pour mobile/AJAX
RewriteRule ^api/products/?$ /api.php?resource=products [L,QSA]
RewriteRule ^api/product/([0-9]+)/?$ /api.php?resource=product&id=$1 [L,QSA]
RewriteRule ^api/cart/?$ /api.php?resource=cart [L,QSA]
RewriteRule ^api/categories/?$ /api.php?resource=categories [L,QSA]

# ==========================================
# GESTION DES STOCKS ET REDIRECTIONS
# ==========================================

# Redirection produits en rupture
RewriteCond %{QUERY_STRING} out_of_stock=1
RewriteRule ^product/([a-z0-9-]+)/?$ /out-of-stock.php?product=$1 [L]

# Redirections promotions temporaires
RewriteCond %{TIME_HOUR} >=14
RewriteCond %{TIME_HOUR} <=18
RewriteRule ^promo/?$ /flash-sale.php [L]

# ==========================================
# MULTI-LANGUES / DEVISES
# ==========================================

# Support multi-langues
RewriteRule ^(fr|en|es|de)/(.*)$ /$2?lang=$1 [L,QSA]

# Devise par défaut selon pays
RewriteCond %{HTTP:CF-IPCountry} ^(US|CA)$ [NC]
RewriteRule ^(.*)$ $1?currency=USD [L,QSA]

RewriteCond %{HTTP:CF-IPCountry} ^(FR|BE|DE|IT|ES)$ [NC]
RewriteRule ^(.*)$ $1?currency=EUR [L,QSA]

📝 Blog WordPress Optimisé

html

# ==========================================
# WORDPRESS BLOG - SÉCURITÉ & PERFORMANCE
# ==========================================

# BEGIN WordPress - Ne pas modifier cette section
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress

# ==========================================
# SÉCURITÉ WORDPRESS RENFORCÉE
# ==========================================

# Masquer wp-config.php
<Files wp-config.php>
    Order allow,deny
    Deny from all
</Files>

# Protéger .htaccess et .htpasswd
<FilesMatch "^\.ht">
    Order allow,deny
    Deny from all
</FilesMatch>

# Bloquer l'accès aux fichiers sensibles
<FilesMatch "(readme\.html|readme\.txt|changelog\.txt|license\.txt)">
    Order allow,deny
    Deny from all
</FilesMatch>

# Protéger wp-includes
<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /
    RewriteRule ^wp-admin/includes/ - [F,L]
    RewriteRule !^wp-includes/ - [S=3]
    RewriteRule ^wp-includes/[^/]+\.php$ - [F,L]
    RewriteRule ^wp-includes/js/tinymce/langs/.+\.php - [F,L]
    RewriteRule ^wp-includes/theme-compat/ - [F,L]
</IfModule>

# Limiter les tentatives de login
<IfModule mod_evasive24.c>
    DOSHashTableSize    3097
    DOSPageCount        2
    DOSPageInterval     1
    DOSSiteCount        50
    DOSSiteInterval     1
    DOSBlockingPeriod   600
</IfModule>

# Bloquer les user-agents suspects
<IfModule mod_rewrite.c>
    RewriteCond %{HTTP_USER_AGENT} (libwww|wget|python|nikto|curl|scan|java|winhttp|clshttp|loader) [NC,OR]
    RewriteCond %{HTTP_USER_AGENT} (%0A|%0D|%27|%3C|%3E|%00) [NC,OR]
    RewriteCond %{HTTP_USER_AGENT} (;|<|>|'|"|\)|\(|%22|%27|%28|%3C|%3E|%00).*(libwww-perl|wget|python|nikto|curl|scan|java|winhttp|HTTrack|clshttp|archiver|loader|email|harvest|extract|grab|miner) [NC]
    RewriteRule .* - [F]
</IfModule>

# ==========================================
# PERFORMANCE WORDPRESS
# ==========================================

# Compression GZIP
<IfModule mod_deflate.c>
    AddOutputFilterByType DEFLATE text/plain
    AddOutputFilterByType DEFLATE text/html
    AddOutputFilterByType DEFLATE text/xml
    AddOutputFilterByType DEFLATE text/css
    AddOutputFilterByType DEFLATE application/xml
    AddOutputFilterByType DEFLATE application/xhtml+xml
    AddOutputFilterByType DEFLATE application/rss+xml
    AddOutputFilterByType DEFLATE application/javascript
    AddOutputFilterByType DEFLATE application/x-javascript
</IfModule>

# Cache Browser
<IfModule mod_expires.c>
    ExpiresActive On

    # Images
    ExpiresByType image/jpg "access plus 1 year"
    ExpiresByType image/jpeg "access plus 1 year"
    ExpiresByType image/gif "access plus 1 year"
    ExpiresByType image/png "access plus 1 year"
    ExpiresByType image/webp "access plus 1 year"

    # CSS, JS, et fonts
    ExpiresByType text/css "access plus 1 month"
    ExpiresByType application/pdf "access plus 1 month"
    ExpiresByType text/javascript "access plus 1 month"
    ExpiresByType application/javascript "access plus 1 month"
    ExpiresByType application/x-javascript "access plus 1 month"
    ExpiresByType font/woff2 "access plus 1 year"

    # HTML
    ExpiresByType text/html "access plus 1 hour"
</IfModule>

# ==========================================
# SEO ET REDIRECTIONS WORDPRESS
# ==========================================

# Force HTTPS
<IfModule mod_rewrite.c>
    RewriteCond %{HTTPS} off
    RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
</IfModule>

# WWW ou non-WWW (choisir une version)
<IfModule mod_rewrite.c>
    RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
    RewriteRule ^(.*)$ https://%1/$1 [R=301,L]
</IfModule>

# Empêcher l'énumération des utilisateurs
<IfModule mod_rewrite.c>
    RewriteCond %{QUERY_STRING} author=\d
    RewriteRule ^(.*)$ /? [L,R=301]
</IfModule>

# ==========================================
# OPTIMISATIONS SPÉCIFIQUES WORDPRESS
# ==========================================

# Désactiver les pingbacks et trackbacks
<Files xmlrpc.php>
    Order allow,deny
    Deny from all
</Files>

# Cache pour les flux RSS
<IfModule mod_headers.c>
    <Files ~ "\.xml$">
        Header set Cache-Control "max-age=3600, public"
    </Files>
</IfModule>

# Optimiser les images WordPress
<IfModule mod_rewrite.c>
    # Servir les images WebP si disponibles
    RewriteCond %{HTTP_ACCEPT} image/webp
    RewriteCond %{REQUEST_FILENAME} \.(png|jpg|jpeg)$
    RewriteCond %{REQUEST_FILENAME}.webp -f
    RewriteRule ^wp-content/uploads/(.*)$ wp-content/uploads/$1.webp [L,T=image/webp]
</IfModule>

# ==========================================
# MAINTENANCE ET DEBUG
# ==========================================

# Mode maintenance (décommenter si nécessaire)
# <IfModule mod_rewrite.c>
#     RewriteCond %{REMOTE_ADDR} !^123\.456\.789\.000$
#     RewriteCond %{REQUEST_URI} !/maintenance.html$
#     RewriteRule ^(.*)$ /maintenance.html [R=503,L]
# </IfModule>

# Désactiver l'affichage d'erreurs PHP en production
php_flag display_startup_errors off
php_flag display_errors off
php_flag html_errors off

.htaccess Maîtrisé !

Vous maîtrisez maintenant la configuration Apache avec .htaccess : redirections, réécriture d'URL, sécurité et optimisation. Passez au niveau supérieur !

🎯 Compétences acquises :

Configuration .htaccess • Redirections 301/302 • URL Rewriting • Sécurité Apache • Optimisation Performance • Protection contre attaques

.htaccess maîtrisé

Redirections, réécriture, sécurité et cache : Apache fait ce que vous lui demandez, dossier par dossier.