.htaccess

Aus ReiseWiki

Wechseln zu: Navigation, Suche

.htaccess (engl. hypertext access „Hypertext-Zugriff“) ist eine Konfigurationsdatei, in der verzeichnisspezifische Einstellungen auf NCSA-kompatiblen Webservern (z. B. Apache) vorgenommen werden können.


Hinweis:
Bei T-Home (Telekom) sind Windows IIS Server im einsatz, dort funktioniert die .htaccess Datei nicht! Webspace mit .htaccess Unterstützung


Inhaltsverzeichnis

URL-Umlenkung / Umleitung

Die Datei alt.html wird nach neu.html weitergeleitet, für Suchmaschinen (SEO) wird ein Statuscode 301 gesendet ("permanenter Redirect"), damit die alte Seite aus dem Index genommen wird.

RewriteEngine on
RewriteBase   /
RewriteRule   ^alt\.html$ neu.html [R=301]


Alle Dateien mit Endung Umleiten

Sollen z.B. alle PDF-Dateien mittels eines Scripts aufgerufen werden, hilft folgendes.


RewriteRule ^(.+)\.pdf$  /script/pdf.php?file=$1.pdf [L,NC,QSA]

Alternative für PHP-Dateien

Der Code-Schnipsel muss direkt am Anfang der Datei stehen, noch vor <html> und Dokumentendeklaration.

<?php
 header('Status: 301 Moved Permanently');
 header('HTTP/1.0 301 Moved Permanently'); 
 header('Location: http://www.example.com/neu.html');
?>


Applikation anhand der Datei - Endung

Wie soll welche Datei interpretiert werden. z.B. im Untenstehendem Beispiel Dateien mit der Endung .php und .php4 werden im PHP V4.3 Ausgeführt

AddType application/x-httpd-php3 .php3
AddType application/x-httpd-php43 .php .php4
AddType application/x-httpd-php5 .php5


Error Dokumente

Automatische weiterleitung, wenn...

401 Unauthorized
Die Anfrage kann nicht ohne gültige Authentifizierung durchgeführt werden. Wie die Authentifizierung durchgeführt werden soll, wird im „WWW-Authenticate“-Header-Feld der Antwort übermittelt.
403 Forbidden
Die Anfrage wurde mangels Berechtigung des Clients nicht durchgeführt. Diese Entscheidung wurde – anders als im Fall des Statuscodes 401 – unabhängig von Authentifizierungsinformationen getroffen, auch etwa wenn eine als HTTPS konfigurierte URI nur mit HTTP aufgerufen wurde.
404 Not Found
Die angeforderte Ressource wurde nicht gefunden. Dieser Statuscode kann ebenfalls verwendet werden, um eine Anfrage ohne näheren Grund abzuweisen. Links, welche auf solche Fehlerseiten verweisen, werden auch als Tote Links bezeichnet.
500 Internal Server Error
Dies ist ein „Sammel-Statuscode“ für unerwartete Serverfehler.
RewriteEngine on
RewriteBase   /
ErrorDocument 401 http://www.example.com/error401.html
ErrorDocument 403 http://www.example.com/error403.html
ErrorDocument 404 http://www.example.com/error404.html
ErrorDocument 500 http://www.example.com/error500.html


Weiterleitung, wenn nicht User Agent

Um z.B. Weiterleitungen für User-Agenten (Suchmaschinen, Spider, Robots) einzurichten

Ist nicht yacybot der HTTP_USER_AGENT, dann leite weiter...

RewriteEngine on
RewriteCond %{HTTP_USER_AGENT} !^yacybot.*$ [NC]
RewriteRule alt.html http://www.example.com/neu.html

Häufige Bots

YaCy [Bot]
yacybot
Google [Bot]
Googlebot
Alta Vista [Bot]
Scooter/


Speziele Robots aussperren

Das [or] bedeuted oder.

Ist der Bot, dann leite weiter auf blocked.html, z.B. für Email Sammler

RewriteEngine on
RewriteBase /
RewriteCond %{HTTP_REFERER} iaea\.org [OR] # spambot
RewriteCond %{REMOTE_ADDR} ^100.100.100.100([6-9])$ [OR] # Bemerkung, Hinweise
RewriteCond %{HTTP_USER_AGENT} ^Widow [OR] 
RewriteCond %{HTTP_USER_AGENT} e?mail.?(sweeper|harvest|collect|wolf) [NC,OR] # spambot 
RewriteCond %{HTTP_USER_AGENT} ^Xaldon\ WebSpider [OR] 
RewriteCond %{HTTP_USER_AGENT} ^Zeus 
RewriteRule ^.* - [F,L] #or RewriteRule .* http://www.example.com/blocked.html [F,L] 


Doppelter Content vermeiden

Doppelter Content (mehrere Internetseiten mit dem gleichen Inhalt) wirkt sich zumeist negativ auf Ihre Positionierung in den Suchmaschinen aus. Alle Serveranfragen die an http://example.com gestellt werden auf http://www.example.com weiterleiten.

RewriteEngine On
RewriteCond %{HTTP_Host} ^example\.com$ [NC]
RewriteRule ^(.*)$ http://www.example.com/$1 [R=301,L]


Virtuelle Dateien erstellen

Aus der Datei www.example.com/index.php?rubrik=1&seite=2, wird im VirtuellenVerzeichnis die NeueDatei.php erstellt.

Der Benutzer bemerkt von alledem nichts.

Der Vorteil ist die optimale Unterbringung von Keywords, Struktur in der Webseite und Benutzerfreundlichkeit. Der User bekommt von alledem nichts mit, da in seiner Adressleiste des Browsers immer das virtuelle Verzeichnis steht.

RewriteEngine On
Options FollowSymLinks
RewriteBase /
RewriteRule VirtuellesVerzeichnis/NeueDatei.php index.php?rubrik=1&seite=2

Security / Sicherheit

# disable directory browsing
Options All -Indexes
# enable directory browsing
Options All +Indexes


Sperre für einzelne Dateien / Verzeichnisse

Dateisperre

<Files "gesperrt.html">
Order Allow,Deny
Deny from All
</Files>
<FilesMatch "\.(htaccess|htpasswd|ini|phps|fla|psd|log|sh)$">
 Order Allow,Deny
 Deny from all
</FilesMatch>


Verzeichnis Sperre

<Files *>
	Order Allow,Deny
	Deny from All
</Files>


Virenschutz / Wurmschutz

Bedingter Zugriffsschutz auf eigene Programme, wenn man als Webmaster zugriff über verschiedene Tools hat.

redirect /BetriebssystemPfad http://stopvirus.invalid # z.B. /windows
redirect /PfadFTP-Programm/ http://stopvirus.invalid  # z.B. /programms/ftp-client/
RedirectMatch (.*)\cmd.exe$ http://stopvirus.invalid$1

Allgemeiner Syntax

[F]
Forbidden: instructs the server to return a 403 Forbidden to the client.
[L]
Last rule: instructs the server to stop rewriting after the preceding directive is processed.
[N]
Next: instructs Apache to rerun the rewrite rule until all rewriting directives have been achieved.
[G]
Gone: instructs the server to deliver Gone (no longer exists) status message.
[P]
Proxy: instructs server to handle requests by mod_proxy
[C]
Chain: instructs server to chain the current rule with the previous rule.
[R]
Redirect: instructs Apache to issue a redirect, causing the browser to request the rewritten/modified URL.
[NC]
GROSS kleinschreibung - wird nicht beachtet
No Case: defines any associated argument as case-insensitive. i.e., "NC" = "No Case".
[PT]
Pass Through: instructs mod_rewrite to pass the rewritten URL back to Apache for further processing.
[OR]
Or: specifies a logical "or" that ties two expressions together such that either one proving true will cause the associated rule to be applied.
[NE]
No Escape: instructs the server to parse output without escaping characters.
[NS]
No Subrequest: instructs the server to skip the directive if internal sub-request.
[QSA]
Append Query String: directs server to add the query string to the end of the expression (URL).
[S=x]
Skip: instructs the server to skip the next "x" number of rules if a match is detected.
[E=variable
value]
Environmental Variable: instructs the server to set the environmental variable "variable" to "value".
[T=MIME-type]
Mime Type: declares the mime type of the target resource.
[]
specifies a character class, in which any character within the brackets will be a match. e.g., [xyz] will match either an x, y, or z.
[]+
character class in which any combination of items within the brackets will be a match. e.g., [xyz]+ will match any number of x’s, y’s, z’s, or any combination of these characters.
[^]
specifies not within a character class. e.g., [^xyz] will match any character that is neither x, y, nor z.
[a-z]
a dash (-) between two characters within a character class ([]) denotes the range of characters between them. e.g., [a-zA-Z] matches all lowercase and uppercase letters from a to z.
a{n}
specifies an exact number, n, of the preceding character. e.g., x{3} matches exactly three x’s.
a{n,}
specifies n or more of the preceding character. e.g., x{3,} matches three or more x’s.
a{n,m}
specifies a range of numbers, between n and m, of the preceding character. e.g., x{3,7} matches three, four, five, six, or seven x’s.
()
used to group characters together, thereby considering them as a single unit. e.g., (perishable)?press will match press, with or without the perishable prefix.
^
denotes the beginning of a regex (regex = regular expression) test string. i.e., begin argument with the proceeding character.
$
denotes the end of a regex (regex = regular expression) test string. i.e., end argument with the previous character.
?
declares as optional the preceding character. e.g., monzas? will match monza or monzas, while mon(za)? will match either mon or monza. i.e., x? matches zero or one of x.
!
declares negation. e.g., “!string” matches everything except “string”.
.
a dot (or period) indicates any single arbitrary character.
-
instructs “not to” rewrite the URL, as in “...domain.com.* - [F]”.
+
matches one or more of the preceding character. e.g., G+ matches one or more G’s, while "+" will match one or more characters of any kind.
matches zero or more of the preceding character. e.g., use “.*” as a wildcard.
|
declares a logical “or” operator. for example, (x|y) matches x or y.
\
escapes special characters ( ^ $ ! . * | ). e.g., use “\.” to indicate/escape a literal dot.
\.
indicates a literal dot (escaped).
/*
zero or more slashes.
.*
zero or more arbitrary characters.
^$
defines an empty string.
^.*$
the standard pattern for matching everything.
[^/.]
defines one character that is neither a slash nor a dot.
[^/.]+
defines any number of characters which contains neither slash nor dot.
http
//
this is a literal statement — in this case, the literal character string, “http://”.
^domain.*
defines a string that begins with the term “domain”, which then may be proceeded by any number of any characters.
^domain\.com$
defines the exact string “domain.com”.
-d
tests if string is an existing directory
-f
tests if string is an existing file
-s
tests if file in test string has a non-zero value

RewriteRule ^\datei.html$ - [F]

^
start of string to be checked
$
end of string to be checked
\datei.html
is the URL to be checked
F
means return Forbidden error

Performance - Seitenaufbau

Allgemeine einstellungen

# Es ist nur im Root Verzeichnis eine htaccess, Server braucht nicht in andere Verzeichnissen suchen
AllowOverride None

# character set - kann dann aus allen HTML Files entfernd werden, uft-8 mit eigenem Charset ersetzen z.B. iso-8859-1
AddDefaultCharset utf-8

# disable the server signature
ServerSignature Off

# set the server timezone
SetEnv TZ Europe/Berlin
# Other Locations see ref http://de2.php.net/manual/en/timezones.php
# SetEnv TZ Europe/London
# SetEnv TZ America/New_York
# SetEnv TZ Etc/GMT+1
# SetEnv TZ UTC


# set the server administrator email
SetEnv SERVER_ADMIN default@example.com

# set the default language
DefaultLanguage en-US

# serve alternate default index page
DirectoryIndex startseite.html
#DirectoryIndex index.php



Einzelne Dateien Cachen - Die Zeitangaben erfolgen in Sekunden

# cache images and flash content for one month
<FilesMatch ".(flv|gif|jpg|jpeg|png|ico|swf|js|css|pdf|txt)$">
Header set Cache-Control "max-age=2592000"
</FilesMatch>
# cache html and htm files for one day
<FilesMatch ".(html|htm)$">
Header set Cache-Control "max-age=43200"
</FilesMatch>
# explicitly disable caching for scripts and other dynamic files
<FilesMatch "\.(pl|php|cgi|spl|scgi|fcgi)$">
Header unset Cache-Control
</FilesMatch>
# alternate method for file caching
ExpiresActive On
ExpiresDefault A604800 # 1 week
ExpiresByType image/x-icon A2419200 # 1 month
ExpiresByType application/x-javascript A2419200 # 1 month
ExpiresByType text/css A2419200 # 1 month
ExpiresByType text/html A300 # 5 minutes
# disable caching for scripts and other dynamic files
<FilesMatch "\.(pl|php|cgi|spl|scgi|fcgi)$">
ExpiresActive Off
</FilesMatch>

Weblinks und weiterführende Informationen

Persönliche Werkzeuge