Die .htaccess-Datei ermöglicht Konfigurationsänderungen auf Verzeichnisebene ohne Zugriff auf die Haupt-Apache-Konfiguration. Ideal für Shared Hosting.
Grundlagen
Was ist .htaccess?
- Dezentrale Konfigurationsdatei für Apache
- Gilt für Verzeichnis und Unterverzeichnisse
- Wird bei jeder Anfrage gelesen (Performance-Overhead)
- Beginnt mit Punkt (versteckte Datei unter Linux)
Voraussetzungen
In der Apache-Konfiguration muss AllowOverride aktiviert sein:
<Directory /var/www/html>
AllowOverride All
</Directory>Datei erstellen
# Erstellen
nano /var/www/html/.htaccess
# Berechtigungen
chmod 644 /var/www/html/.htaccessWeiterleitungen (Redirects)
Einfache Weiterleitung
# Einzelne Seite
Redirect 301 /alte-seite.html /neue-seite.html
# Ganzes Verzeichnis
Redirect 301 /blog /neuer-blog
# Zu anderer Domain
Redirect 301 /seite https://andere-domain.de/seiteHTTP-Statuscodes
| Code | Bedeutung | |------|-----------| | 301 | Permanent verschoben (SEO-relevant) | | 302 | Temporär verschoben | | 303 | See Other | | 307 | Temporary Redirect |
Mit mod_rewrite
RewriteEngine On
# HTTP zu HTTPS
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
# www zu non-www
RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
RewriteRule ^(.*)$ https://%1/$1 [R=301,L]
# non-www zu www
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}/$1 [R=301,L]SEO-freundliche URLs
RewriteEngine On
# Endung .html entfernen
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule ^(.*)$ $1.html [L]
# /produkt/123 → produkt.php?id=123
RewriteRule ^produkt/([0-9]+)/?$ produkt.php?id=$1 [L,QSA]
# /kategorie/name → kategorie.php?name=name
RewriteRule ^kategorie/([a-z-]+)/?$ kategorie.php?name=$1 [L,QSA]Zugriffskontrolle
IP-basierte Beschränkung
# Nur bestimmte IPs erlauben
<RequireAll>
Require ip 192.168.1.0/24
Require ip 10.0.0.50
</RequireAll>
# Bestimmte IPs blockieren
<RequireAll>
Require all granted
Require not ip 192.168.1.100
</RequireAll>Passwortschutz (Basic Auth)
# .htaccess
AuthType Basic
AuthName "Geschützter Bereich"
AuthUserFile /var/www/.htpasswd
Require valid-userPasswort-Datei erstellen:
htpasswd -c /var/www/.htpasswd usernameVerzeichnis-Listing deaktivieren
Options -IndexesDateizugriff blockieren
# Bestimmte Dateien blockieren
<FilesMatch "\.(htaccess|htpasswd|ini|log|sh|sql)$">
Require all denied
</FilesMatch>
# Einzelne Datei blockieren
<Files "config.php">
Require all denied
</Files>
# Versteckte Dateien blockieren
<FilesMatch "^\.">
Require all denied
</FilesMatch>Caching und Performance
Browser-Caching
<IfModule mod_expires.c>
ExpiresActive On
# Standard
ExpiresDefault "access plus 1 month"
# HTML
ExpiresByType text/html "access plus 1 hour"
# CSS/JS
ExpiresByType text/css "access plus 1 year"
ExpiresByType application/javascript "access plus 1 year"
# Bilder
ExpiresByType image/jpeg "access plus 1 year"
ExpiresByType image/png "access plus 1 year"
ExpiresByType image/gif "access plus 1 year"
ExpiresByType image/webp "access plus 1 year"
ExpiresByType image/svg+xml "access plus 1 year"
# Fonts
ExpiresByType font/woff2 "access plus 1 year"
ExpiresByType font/woff "access plus 1 year"
</IfModule>Gzip-Komprimierung
<IfModule mod_deflate.c>
# Komprimierbare Typen
AddOutputFilterByType DEFLATE text/html
AddOutputFilterByType DEFLATE text/css
AddOutputFilterByType DEFLATE text/javascript
AddOutputFilterByType DEFLATE application/javascript
AddOutputFilterByType DEFLATE application/json
AddOutputFilterByType DEFLATE application/xml
AddOutputFilterByType DEFLATE image/svg+xml
# Bereits komprimierte Dateien ausschließen
SetEnvIfNoCase Request_URI \.(?:gif|jpe?g|png|webp|zip|gz)$ no-gzip
</IfModule>ETag entfernen
<IfModule mod_headers.c>
Header unset ETag
</IfModule>
FileETag NoneSicherheitsheader
<IfModule mod_headers.c>
# Clickjacking verhindern
Header always set X-Frame-Options "SAMEORIGIN"
# XSS-Schutz
Header always set X-XSS-Protection "1; mode=block"
# MIME-Sniffing verhindern
Header always set X-Content-Type-Options "nosniff"
# Referrer-Policy
Header always set Referrer-Policy "strict-origin-when-cross-origin"
# HSTS (nur bei HTTPS!)
Header always set Strict-Transport-Security "max-age=31536000; includeSubDomains"
# Content-Security-Policy (Beispiel)
Header always set Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'"
</IfModule>Fehlerseiten
# Eigene Fehlerseiten
ErrorDocument 400 /errors/400.html
ErrorDocument 401 /errors/401.html
ErrorDocument 403 /errors/403.html
ErrorDocument 404 /errors/404.html
ErrorDocument 500 /errors/500.html
# Oder mit Nachricht
ErrorDocument 404 "Seite nicht gefunden"
# Oder externe URL
ErrorDocument 404 https://example.com/404PHP-Einstellungen
# PHP-Werte setzen (wenn erlaubt)
php_value upload_max_filesize 64M
php_value post_max_size 64M
php_value max_execution_time 300
php_value memory_limit 256M
# PHP-Flags
php_flag display_errors Off
php_flag log_errors OnMIME-Types
# Neue MIME-Types hinzufügen
AddType application/font-woff2 .woff2
AddType application/json .json
AddType image/webp .webp
AddType image/avif .avif
# Standard-Zeichensatz
AddDefaultCharset UTF-8
# Spezifisch für Dateityp
AddCharset UTF-8 .html .css .js .json .xmlHotlink-Schutz
Verhindert, dass andere Websites Ihre Bilder einbinden:
RewriteEngine On
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^https://(www\.)?ihre-domain\.de [NC]
RewriteRule \.(jpg|jpeg|png|gif|webp)$ - [F,NC]
# Oder Ersatzbild anzeigen
RewriteRule \.(jpg|jpeg|png|gif|webp)$ /images/hotlink-blocked.png [R,NC]Vollständiges Beispiel
# ===== GRUNDEINSTELLUNGEN =====
Options -Indexes
DirectoryIndex index.php index.html
# ===== SICHERHEIT =====
<FilesMatch "\.(htaccess|htpasswd|ini|log|sh|sql|env)$">
Require all denied
</FilesMatch>
# ===== WEITERLEITUNGEN =====
RewriteEngine On
# HTTPS erzwingen
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
# www zu non-www
RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
RewriteRule ^(.*)$ https://%1/$1 [R=301,L]
# ===== FEHLERSEITEN =====
ErrorDocument 404 /404.html
ErrorDocument 500 /500.html
# ===== CACHING =====
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType text/html "access plus 1 hour"
ExpiresByType text/css "access plus 1 year"
ExpiresByType application/javascript "access plus 1 year"
ExpiresByType image/jpeg "access plus 1 year"
ExpiresByType image/png "access plus 1 year"
ExpiresByType image/webp "access plus 1 year"
</IfModule>
# ===== KOMPRIMIERUNG =====
<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/html text/css application/javascript
</IfModule>
# ===== SICHERHEITSHEADER =====
<IfModule mod_headers.c>
Header always set X-Frame-Options "SAMEORIGIN"
Header always set X-Content-Type-Options "nosniff"
Header always set X-XSS-Protection "1; mode=block"
</IfModule>Troubleshooting
Syntax prüfen
apachectl configtestHäufige Fehler
500 Internal Server Error:
- Syntax-Fehler in .htaccess
- Modul nicht geladen (z.B. mod_rewrite)
- AllowOverride nicht gesetzt
Weiterleitung funktioniert nicht:
- RewriteEngine On vergessen
- mod_rewrite nicht aktiviert:
a2enmod rewrite
Passwortschutz funktioniert nicht:
- Pfad zu .htpasswd falsch
- Datei-Berechtigungen prüfen
Module prüfen/aktivieren
# Installierte Module auflisten
apachectl -M
# Module aktivieren
a2enmod rewrite
a2enmod expires
a2enmod headers
a2enmod deflate
# Apache neu laden
systemctl reload apache2Fazit
.htaccess bietet flexible Konfigurationsmöglichkeiten ohne Server-Zugriff. Für Weiterleitungen, Caching, Sicherheitsheader und Zugriffskontrolle ist sie unverzichtbar. Bei Root-Zugriff sollten Sie Konfigurationen jedoch in die Apache-Config verschieben – das ist performanter, da .htaccess bei jeder Anfrage gelesen wird.