Technical Documentation: phanan/htaccess
ℹ️ Provenance: Multi-Tier Ingestion · CodeWiki Reference
Overview (`README.md`)
.htaccess Snippets [](https://github.com/sindresorhus/awesome)
A collection of useful .htaccess snippets, all in one place.
[!NOTE]
.htaccessfiles are for people that do not have rights to edit the main server configuration file. They are intrinsically slower and more complicated than using the main config. Please see the howto in the httpd documentation for further details.
[!WARNING]
While dropping the snippet into an.htaccessfile is most of the time sufficient, there are cases when certain modifications might be required. Use at your own risk.
[!IMPORTANT]
These snippets are for Apache 2.4. If you are still using Apache 2.2, check the2.2branch. For details on the breaking changes between 2.2 and 2.4, see the upgrading document as well as this issue.
Credits
What we are doing here is mostly collecting useful snippets from all over the interwebs (for example, a good chunk is from Apache Server Configs) into one place. While we’ve been trying to credit where due, things might be missing. If you believe anything here is your work and credits should be given, let us know, or just send a PR.
Table of Contents
- Rewrite and Redirection
- Force www
- Force www in a Generic Way
- Force non-www
- Force non-www in a Generic Way
- Force HTTPS
- Force HTTPS Behind a Proxy
- Force Trailing Slash
- Remove Trailing Slash
- Redirect a Single Page
- Redirect Using RedirectMatch
- Alias a Single Directory
- Alias Paths to Script
- Redirect an Entire Site
- Alias "Clean" URLs
- Exclude a URL from Redirection
- Security
- Deny All Access
- Deny All Access Except Yours
- Allow All Access Except Spammers'
- Deny Access to Hidden Files and Directories
- Deny Access to Backup and Source Files
- Disable Directory Browsing
- Disable Image Hotlinking
- Disable Image Hotlinking for Specific Domains
- Password Protect a Directory
- Password Protect a File or Several Files
- Block Visitors by Referrer
- Block Specific User Agents
- Prevent Framing the Site
- Content Security Policy (CSP)
- Prevent MIME Type Sniffing
- Set Referrer Policy
- Set Permissions Policy
- Remove Server Signature
- Performance
- Miscellaneous
Rewrite and Redirection
Note: It is assumed that you have mod_rewrite installed and enabled.
Force www
RewriteEngine on
RewriteCond %{HTTP_HOST} ^example\.com [NC]
RewriteRule ^(.*)$ https://www.example.com/$1 [L,R=301,NC]Force www in a Generic Way
RewriteCond %{HTTP_HOST} !^$
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTPS}s ^on(s)|
RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]This works for any domain. Source
Force non-www
It’s still open for debate whether www or non-www is the way to go, so if you happen to be a fan of bare domains, here you go:
RewriteEngine on
RewriteCond %{HTTP_HOST} ^www\.example\.com [NC]
RewriteRule ^(.*)$ https://example.com/$1 [L,R=301]Force non-www in a Generic Way
RewriteEngine on
RewriteCond %{HTTP_HOST} ^www\.
RewriteCond %{HTTPS}s ^on(s)|off
RewriteCond http%1://%{HTTP_HOST} ^(https?://)(www\.)?(.+)$
RewriteRule ^ %1%3%{REQUEST_URI} [R=301,L]Force HTTPS
RewriteEngine on
RewriteCond %{HTTPS} !on
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}
# Note: It’s also recommended to enable HTTP Strict Transport Security (HSTS)
# on your HTTPS website to help prevent man-in-the-middle attacks.
# See https://developer.mozilla.org/en-US/docs/Web/Security/HTTP_strict_transport_security
<IfModule mod_headers.c>
# Remove "includeSubDomains" if you don't want to enforce HSTS on all subdomains
Header always set Strict-Transport-Security "max-age=31536000;includeSubDomains"
</IfModule>Force HTTPS Behind a Proxy
Useful if you have a proxy in front of your server performing TLS termination.
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}Force Trailing Slash
RewriteCond %{REQUEST_URI} /+[^\.]+$
RewriteRule ^(.+[^/])$ %{REQUEST_URI}/ [R=301,L]Remove Trailing Slash
This snippet will redirect paths ending in slashes to their non-slash-terminated counterparts (except for actual directories), e.g. https://www.example.com/blog/ to https://www.example.com/blog. This is important for SEO, since it’s recommended to have a canonical URL for every page.
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} (.+)/$
RewriteRule ^ %1 [R=301,L]Redirect a Single Page
Redirect 301 /oldpage.html https://www.example.com/newpage.html
Redirect 301 /oldpage2.html https://www.example.com/folder/Redirect Using RedirectMatch
RedirectMatch 301 /subdirectory(.*) https://www.newsite.com/newfolder/$1
RedirectMatch 301 ^/(.*).htm$ /$1.html
RedirectMatch 301 ^/200([0-9])/([^01])(.*)$ /$2$3
RedirectMatch 301 ^/category/(.*)$ /$1
RedirectMatch 301 ^/(.*)/htaccesselite-ultimate-htaccess-article.html(.*) /htaccess/htaccess.html
RedirectMatch 301 ^/(.*).html/1/(.*) /$1.html$2
RedirectMatch 301 ^/manual/(.*)$ https://www.php.net/manual/$1
RedirectMatch 301 ^/old-directory/(.*)$ /new-directory/$1
RedirectMatch 301 ^/z/(.*)$ https://static.askapache.com/$1Alias a Single Directory
RewriteEngine On
RewriteRule ^source-directory/(.*) /target-directory/$1 [R=301,L]Alias Paths to Script
FallbackResource /index.fcgiThis example has an index.fcgi file in some directory, and any requests within that directory that fail to resolve a filename/directory will be sent to the index.fcgi script. It’s good if you want baz.foo/some/cool/path to be handled by baz.foo/index.fcgi (which also supports requests to baz.foo) while maintaining baz.foo/css/style.css and the like. Get access to the original path from the PATH_INFO environment variable, as exposed to your scripting environment.
RewriteEngine On
RewriteRule ^$ index.fcgi/ [QSA,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.fcgi/$1 [QSA,L]This is a less efficient version of the FallbackResource directive (because using mod_rewrite is more complex than just handling the FallbackResource directive), but it’s also more flexible.
Redirect an Entire Site
Redirect 301 / https://newsite.com/This way does it with links intact. That is www.oldsite.com/some/crazy/link.html will become www.newsite.com/some/crazy/link.html. This is extremely helpful when you are just “moving” a site to a new domain. Source
Alias “Clean” URLs
This snippet lets you use “clean” URLs -- those without a PHP extension, e.g. example.com/users instead of example.com/users.php.
RewriteEngine On
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule ^([^.]+)$ $1.php [NC,L]Exclude URL from Redirection
This snippet allows you to exclude a URL from redirection. For example, if you have redirection rules setup but want to exclude robots.txt so search engines can access that URL as expected.
RewriteEngine On
RewriteRule ^robots.txt - [L]Security
Deny All Access
Require all deniedBut wait, this will lock you out from your content as well! Thus introducing...
Deny All Access Except Yours
Require all denied
Require ip xxx.xxx.xxx.xxxxxx.xxx.xxx.xxx is your IP. If you replace the last three digits with 0/12 for example, this will specify a range of IPs within the same network, thus saving you the trouble to list all allowed IPs separately. Source
Now of course there's a reversed version:
Allow All Access Except Spammers'
Require all granted
Require not ip xxx.xxx.xxx.xxx
Require not ip xxx.xxx.xxx.xxyDeny Access to Hidden Files and Directories
Hidden files and directories (those whose names start with a dot .) should most, if not all, of the time be secured. For example: .htaccess, .htpasswd, .git, .hg...
RewriteCond %{SCRIPT_FILENAME} -d [OR]
RewriteCond %{SCRIPT_FILENAME} -f
RewriteRule "(^|/)\." - [F]Alternatively, you can just raise a “Not Found” error, giving the attacker no clue:
RedirectMatch 404 /\..*$Deny Access to Backup and Source Files
These files may be left by some text/HTML editors (like Vi/Vim) and pose a great security danger if exposed to public.
<FilesMatch "(\.(bak|config|dist|fla|inc|ini|log|psd|sh|sql|swp)|~)$">
Require all denied
</FilesMatch>Disable Directory Browsing
Options All -IndexesDisable Image Hotlinking
RewriteEngine on
# Remove the following line if you want to block blank referrer too
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^https?://(.+\.)?example.com [NC]
RewriteRule \.(jpe?g|png|gif|bmp|webp|avif|svg|ico)$ - [NC,F,L]
# If you want to display a “blocked” banner in place of the hotlinked image,
# replace the above rule with:
# RewriteRule \.(jpe?g|png|gif|bmp|webp|avif|svg|ico) https://example.com/blocked.png [R,L]Disable Image Hotlinking for Specific Domains
Sometimes you want to disable image hotlinking from some bad guys only.
RewriteEngine on
RewriteCond %{HTTP_REFERER} ^https?://(.+\.)?badsite\.com [NC,OR]
RewriteCond %{HTTP_REFERER} ^https?://(.+\.)?badsite2\.com [NC,OR]
RewriteRule \.(jpe?g|png|gif|bmp|webp|avif|svg|ico)$ - [NC,F,L]
# If you want to display a “blocked” banner in place of the hotlinked image,
# replace the above rule with:
# RewriteRule \.(jpe?g|png|gif|bmp|webp|avif|svg|ico) https://example.com/blocked.png [R,L]Password Protect a Directory
First you need to create a .htpasswd file somewhere in the system:
htpasswd -c /home/fellowship/.htpasswd boromirThen you can use it for authentication:
AuthType Basic
AuthName "One does not simply"
AuthUserFile /home/fellowship/.htpasswd
Require valid-userPassword Protect a File or Several Files
AuthName "One still does not simply"
AuthType Basic
AuthUserFile /home/fellowship/.htpasswd
<Files "one-ring.o">
Require valid-user
</Files>
<FilesMatch ^((one|two|three)-rings?\.o)$>
Require valid-user
</FilesMatch>Block Visitors by Referrer
This denies access for all users who are coming from (referred by) a specific domain.
Source
RewriteEngine on
# Options +FollowSymlinks
RewriteCond %{HTTP_REFERER} somedomain\.com [NC,OR]
RewriteCond %{HTTP_REFERER} anotherdomain\.com
RewriteRule .* - [F]Block Specific User Agents
This will block specific user agents from accessing your site, useful for blocking scrapers and bad bots.
RewriteEngine on
RewriteCond %{HTTP_USER_AGENT} BadBot [NC,OR]
RewriteCond %{HTTP_USER_AGENT} EvilScraper [NC]
RewriteRule .* - [F,L]Prevent Framing the Site
This prevents the website to be framed (i.e. put into an iframe tag), when still allows framing for a specific URI.
SetEnvIf Request_URI "/starry-night" allow_framing=true
Header set X-Frame-Options SAMEORIGIN env=!allow_framingContent Security Policy (CSP)
A Content Security Policy header helps mitigate cross-site scripting (XSS) and other code injection attacks by declaring which dynamic resources are allowed to load.
<IfModule mod_headers.c>
Header set Content-Security-Policy "default-src 'self'; script-src 'self'; style-src 'self'"
</IfModule>Adjust the directives to fit your needs. See the CSP reference for all available directives.
Prevent MIME Type Sniffing
This prevents browsers from trying to guess ("sniff") the MIME type of a resource, which can have security implications. The browser will trust what the server says and block the resource if it doesn't match the expected type.
<IfModule mod_headers.c>
Header set X-Content-Type-Options "nosniff"
</IfModule>Set Referrer Policy
Control how much referrer information is included with requests. This helps protect user privacy by preventing the full URL from leaking to external sites.
<IfModule mod_headers.c>
Header set Referrer-Policy "strict-origin-when-cross-origin"
</IfModule>Set Permissions Policy
Restrict which browser features your site can use, such as camera, microphone, geolocation, etc.
<IfModule mod_headers.c>
Header set Permissions-Policy "camera=(), microphone=(), geolocation=(), interest-cohort=()"
</IfModule>Remove Server Signature
Prevent Apache from exposing its version number and OS information in HTTP headers and error pages.
ServerSignature OffPerformance
Compress Text Files
/* Detailed source-code truncated for AI context efficiency. */Set Expires Headers
Expires headers tell the browser whether they should request a specific file from the server or just grab it from the cache. It is advisable to set static content's expires headers to something far in the future.
If you don’t control versioning with filename-based cache busting, consider lowering the cache time for resources like CSS and JS to something like 1 week. Source
/* Detailed source-code truncated for AI context efficiency. */Set Cache-Control Headers
Cache-Control headers provide more fine-grained control over browser caching than Expires headers. You can use both together for maximum compatibility.
<IfModule mod_headers.c>
# Cache CSS and JS for 1 year
<FilesMatch "\.(css|js)$">
Header set Cache-Control "max-age=31536000, public"
</FilesMatch>
# Cache images for 1 month
<FilesMatch "\.(jpe?g|png|gif|webp|avif|svg|ico)$">
Header set Cache-Control "max-age=2592000, public"
</FilesMatch>
# Cache fonts for 1 month
<FilesMatch "\.(woff2?|ttf|otf)$">
Header set Cache-Control "max-age=2592000, public"
</FilesMatch>
# Do not cache HTML
<FilesMatch "\.(html|htm)$">
Header set Cache-Control "no-cache, no-store, must-revalidate"
</FilesMatch>
</IfModule>Turn eTags Off
By removing the ETag header, you disable caches and browsers from being able to validate files, so they are forced to rely on your Cache-Control and Expires header. Source
<IfModule mod_headers.c>
Header unset ETag
</IfModule>
FileETag NoneMiscellaneous
Set PHP Variables
php_value <key> <val>
# For example:
php_value upload_max_filesize 50M
php_value max_execution_time 240Custom Error Pages
ErrorDocument 500 "Houston, we have a problem."
ErrorDocument 401 https://error.example.com/mordor.html
ErrorDocument 404 /errors/halflife3.htmlCustom Maintenance Page
Redirect all traffic to a maintenance page while still allowing access from a specific IP address.
RewriteEngine on
RewriteCond %{REMOTE_ADDR} !^xxx\.xxx\.xxx\.xxx
RewriteCond %{REQUEST_URI} !/maintenance.html$ [NC]
RewriteCond %{REQUEST_URI} !\.(css|js|png|jpe?g|gif|svg|ico)$ [NC]
RewriteRule .* /maintenance.html [R=503,L]Replace xxx.xxx.xxx.xxx with your IP address to retain access while the site is under maintenance.
Force Downloading
Sometimes you want to force the browser to download some content instead of displaying it.
<Files *.md>
ForceType application/octet-stream
Header set Content-Disposition attachment
</Files>Now there is a yang to this yin:
Prevent Downloading
Sometimes you want to force the browser to display some content instead of downloading it.
<FilesMatch "\.(tex|log|aux)$">
Header set Content-Type text/plain
</FilesMatch>Allow Cross-Domain Fonts
CDN-served webfonts might not work in Firefox due to CORS. This snippet solves the problem.
<IfModule mod_headers.c>
<FilesMatch "\.(otf|ttc|ttf|woff|woff2)$">
Header set Access-Control-Allow-Origin "*"
</FilesMatch>
</IfModule>Enable CORS
Enable Cross-Origin Resource Sharing (CORS) for your site, allowing other domains to make requests to your server.
<IfModule mod_headers.c>
Header set Access-Control-Allow-Origin "*"
Header set Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS"
Header set Access-Control-Allow-Headers "Content-Type, Authorization"
</IfModule>To restrict access to specific domains, replace * with the domain, e.g. https://example.com.
Auto UTF-8 Encode
Your text content should always be UTF-8 encoded, no?
# Use UTF-8 encoding for anything served text/plain or text/html
AddDefaultCharset utf-8
# Force UTF-8 for a number of file formats
AddCharset utf-8 .atom .css .js .json .rss .vtt .xmlSet Custom MIME Types
Define custom MIME types for file formats that Apache may not recognize by default.
AddType application/manifest+json .webmanifest
AddType application/wasm .wasm
AddType application/x-ndjson .ndjson
AddType text/vtt .vttSwitch to Another PHP Version
If you’re on a shared host, chances are there are more than one version of PHP installed, and sometimes you want a specific version for your website. The following snippet should switch the PHP version for you.
AddHandler application/x-httpd-php84 .php
# Alternatively, you can use AddType
AddType application/x-httpd-php84 .phpServe WebP/AVIF Images
If a modern format image (AVIF or WebP) with the same name exists alongside the original jpg/png, it will be served instead. AVIF is preferred over WebP when the browser supports both.
RewriteEngine On
# Serve AVIF if supported and available
RewriteCond %{HTTP_ACCEPT} image/avif
RewriteCond %{DOCUMENT_ROOT}/$1.avif -f
RewriteRule (.+)\.(jpe?g|png)$ $1.avif [T=image/avif,E=accept:1]
# Otherwise, serve WebP if supported and available
RewriteCond %{HTTP_ACCEPT} image/webp
RewriteCond %{DOCUMENT_ROOT}/$1.webp -f
RewriteRule (.+)\.(jpe?g|png)$ $1.webp [T=image/webp,E=accept:1]Overview (`Translations/French/README.md`)
.htaccess Snippets [](https://github.com/sindresorhus/awesome)
Une collection utile de fragments de configuration de fichier
.htaccess, le
tout regroupé dans un seul endroit.
Avertissement : Bien que l'extrait mis dans un fichier .htaccess est la
plupart du temps suffisant, il ya des cas où certaines modifications pourraient
être nécessaires. À utiliser à vos propres risques.
IMPORTANT : Apache 2.4 a introduit quelques changements de rupture,
notamment dans la configuration de contrôle d'accès. Pour plus d'information,
consultez le
document de mise à niveau
ainsi que cette issue.
Crédits
Ce que nous faisons ici est principalement la collection d'extraits pratiques en
provenance d'un peu partout sur le web, par exemple, une bonne partie provient
du dépôt Apache Server Configs.
Bien qu'ayant essayé de créditer la bonne personne, des éléments peuvent être
manquants. Si vous pensez que quelque chose ici provient de votre travail et que
vous devriez en être crédité, faites le moi savoir, ou faites une PR.
Table des matières
- Réécriture et redirection
- Forcer www
- Forcer www d'une manière générique
- Forcer non-www
- Forcer non-www d'une manière générique
- Forcer HTTPS
- Forcer HTTPS derrière un proxy
- Forcer le slash de fin
- Supprimer le slash de fin
- Rediriger une seule page
- Alias pour un seul dossier
- Alias de chemins vers un script
- Rediriger un site entier
- Alias en URLs propres
- Sécurité
- Refuser tout accès
- Refuser tout accès sauf soi-même
- Autoriser tout accès sauf aux spammeurs'
- Refuser l'accès aux fichiers et répertoires cachés
- Refuser l'accès aux sources et fichiers de sauvegarde
- Désactiver la navigation de dossier
- Désactiver le hotlink des images
- Désactiver le hotlink des images pour des domaines spécifiques
- Protéger un dossier par mot de passe
- Protéger un ou plusieurs fichiers par mot de passe
- Performance
- Divers
Réécriture et redirection
Remarque: On suppose avoir le module mod_rewrite installé et activé.
Forcer www
RewriteEngine on
RewriteCond %{HTTP_HOST} ^example\.com [NC]
RewriteRule ^(.*)$ http://www.example.com/$1 [L,R=301,NC]Forcer www d'une manière générique
RewriteCond %{HTTP_HOST} !^$
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTPS}s ^on(s)|
RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]Cela fonctionne pour tous les domaines.
Source
Forcer non-www
C'est toujours
en cours
de débat selon s'il faut
prévilégier la forme avec ou sans www, donc si vous êtes un fan de domaine
"à nu", ceci est pour vous :
RewriteEngine on
RewriteCond %{HTTP_HOST} ^www\.example\.com [NC]
RewriteRule ^(.*)$ http://example.com/$1 [L,R=301]Forcer non-www d'une manière générique
RewriteEngine on
RewriteCond %{HTTP_HOST} ^www\.
RewriteCond %{HTTPS}s ^on(s)|off
RewriteCond http%1://%{HTTP_HOST} ^(https?://)(www\.)?(.+)$
RewriteRule ^ %1%3%{REQUEST_URI} [R=301,L]Forcer HTTPS
RewriteEngine on
RewriteCond %{HTTPS} !on
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}Forcer HTTPS derrière un proxy
Ceci est utile si vous avez un proxy devant votre serveur faisant une
termination TLS :
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}Forcer le slash de fin
RewriteCond %{REQUEST_URI} /+[^\.]+$
RewriteRule ^(.+[^/])$ %{REQUEST_URI}/ [R=301,L]Supprimer le slash de fin
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$ /$1 [R=301,L]Rediriger une seule page
Redirect 301 /anciennepage.html http://www.votresite.com/nouvellepage.html
Redirect 301 /anciennepage2.html http://www.votresite.com/dossier/Alias pour un seul dossier
RewriteEngine On
RewriteRule ^source-directory/(.*) target-directory/$1Alias de chemins vers un script
FallbackResource /index.fcgiCet exemple a un fichier index.fcgi dans un répertoire, et toutes les requêtes
à l'intérieur de ce dossier qui ne peuvent résoudre le fichier/dossier demandé
seront renvoyées vers le script index.fcgi. Ceci est utile si vous souhaitez
que baz.foo/une/route/sympa soit manipulé par baz.foo/index.fcgi (qui prend
également en charge les demandes vers baz.foo) tout en maintenantbaz.foo/css/style.css ou autre fonctionnels. Accédez au chemin d'origine de la
variable d'environnement PATH_INFO, comme exposé à votre environnement de
scriptage.
RewriteEngine On
RewriteRule ^$ index.fcgi/ [QSA,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.fcgi/$1 [QSA,L]Ceci est une version moins efficace de la directive FallbackResource (car
l'utilisation de mod_rewrite est plus complexe que de maintenir la directiveFallbackResource), mais offre d'avantage de flexibilité.
Rediriger un site entier
Redirect 301 / http://nouveausite.com/Ceci laisse les liens intacts. Ainsi anciensite.com/lien/super/genial.html
deviendra nouveausite.com/lien/super/genial.html. Cela est très pratique
lorsque vous souhaitez déplacer un site vers un nouveau domaine.
Alias en URLs propres
Ce snippet vous permet d'utiliser des "URLs propres" –celles sans extension–,
par exemple : example.com/users à la place de example.com/users.php.
RewriteEngine On
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule ^([^.]+)$ $1.php [NC,L]Securité
Refuser tout accès
## Apache 2.2
Deny from all
## Apache 2.4
# Require all deniedMais… ceci vous bloquera vous également ! Si ce n'est pas ce que vous souhaitez,
la partie suivante est sûrement faite pour vous !
Refuser tout accès sauf soi-même
## Apache 2.2
Order deny,allow
Deny from all
Allow from xxx.xxx.xxx.xxx
## Apache 2.4
# Require all denied
# Require ip xxx.xxx.xxx.xxxEn remplaçant xxx.xxx.xxx.xxx par votre adresse IP, vous n'autoriserez l'accès
à votre site que par vous. Si vous remplacez les 3 dernièrs numéros par 0/12
par exemple, ceci spécifiera un intervalle d'adresses IPs à l'intérieur d'un
même réseau, vous évitant ainsi de lister toutes les IPs autorisées
individuellement.
Bien sûr, il y a la version inverse :
Autoriser tout accès sauf aux spammeurs
## Apache 2.2
Order deny,allow
Deny from xxx.xxx.xxx.xxx
Deny from xxx.xxx.xxx.xxy
## Apache 2.4
# Require all granted
# Require not ip xxx.xxx.xxx.xxx
# Require not ip xxx.xxx.xxx.xxyRefuser l'accès aux fichiers et dossiers cachés
Les fichiers et dossiers cachés (ceux dont les noms commencent par un point .)
devraient être pour la majorité d'entre eux sécurisés. On ne devrait par exemple
pas avoir accès aux éléments suivants : .htaccess, .htpasswd, .git,.hg...
RewriteCond %{SCRIPT_FILENAME} -d [OR]
RewriteCond %{SCRIPT_FILENAME} -f
RewriteRule "(^|/)\." - [F]Une autre solution serait de lever une erreur 404 Not Found, ne donnant aucun
indice à l'attaquant quant à l'existance de la ressource :
RedirectMatch 404 /\..*$Refuser l'accès aux sources et fichiers de sauvegarde
Ces fichiers peuvent être laissés par certains éditeurs de texte/html (comme
Vi/Vim) et poser un grand danger en terme de sécurité, quand quelqu'un y a
accès.
<FilesMatch "(\.(bak|config|dist|fla|inc|ini|log|psd|sh|sql|swp)|~)$">
## Apache 2.2
Order allow,deny
Deny from all
Satisfy All
## Apache 2.4
# Require all denied
</FilesMatch>Désactiver la navigation de dossier
Options All -IndexesDésactiver le hotlink des images
RewriteEngine on
# Enlever la ligne ci-dessous si vous souhaitez bloquer le referrer vide
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http(s)?://(.+\.)?votredomaine.com [NC]
RewriteRule \.(jpg|jpeg|png|gif|bmp)$ - [NC,F,L]
# Si vous souhaitez afficher une bannière "Bloquée" d'url 'blocked.png' au lieu
# du hotlink de l'image, replacez la règle ci-dessus par celle-ci :
# RewriteRule \.(jpg|jpeg|png|gif|bmp) http://votredomaine.com/blocked.png [R,L]Désactiver le hotlink des images pour des domaines spécifiques
Parfois vous souhaitez désactiver le hotlink d'images seulement pour quelques
domaines spécifiques. L'extrait suivant devrait vous aider :
RewriteEngine on
RewriteCond %{HTTP_REFERER} ^http(s)?://(.+\.)?mauvaissite\.com [NC,OR]
RewriteCond %{HTTP_REFERER} ^http(s)?://(.+\.)?mauvaissite2\.com [NC,OR]
RewriteRule \.(jpg|jpeg|png|gif)$ - [NC,F,L]
# Si vous souhaitez afficher une bannière "Bloquée" d'url 'blocked.png' au lieu
# du hotlink de l'image, replacez la règle ci-dessus par celle-ci :
# RewriteRule \.(jpg|jpeg|png|gif|bmp) http://votredomaine.com/blocked.png [R,L]Protéger un dossier par mot de passe
D'abord, vous aurez besoin de créer un fichier .htpasswd quelque part sur le
système, avec l'aide de la commande suivante :
htpasswd -c /home/fellowship/.htpasswd boromirEnsuite, vous pouvez utiliser ceci pour activer l'authentification :
AuthType Basic
AuthName "One does not simply"
AuthUserFile /home/fellowship/.htpasswd
Require valid-userProtéger un ou plusieurs fichiers par mot de passe
AuthName "One still does not simply"
AuthType Basic
AuthUserFile /home/fellowship/.htpasswd
<Files "one-ring.o">
Require valid-user
</Files>
<FilesMatch ^((one|two|three)-rings?\.o)$>
Require valid-user
</FilesMatch>Performance
Compresser les fichiers texte
/* Detailed source-code truncated for AI context efficiency. */Ajouter l'en-tête "Expires"
L'en-tête Expires indique au navigateur s'il doit effectuer une requête au
serveur pour récupérer un fichier spécifique ou bien se contenter du cache. On
peut conseiller pour les contenus statiques un en-tête d'expiration loin dans le
futur.
Si vous n'utilisez pas la méthode du nom de fichier modifié par un système de
contrôle de version, vous devriez diminuer le temps de cache des ressources
telles que les fichiers CSS ou JS vers quelque chose proche de la semaine.
/* Detailed source-code truncated for AI context efficiency. */Désactiver eTags
En retirant l'en-tête "eTag", vous empêchez le cache et les navigateurs de
pouvoir valider les fichiers, ils sont donc forcés de se baser sur le
Cache-Control (contrôle de cache) et les Expires header (en-tête d'expiration).
<IfModule mod_headers.c>
Header unset ETag
</IfModule>
FileETag NoneDivers
Définir des variables PHP
php_value <key> <val>
# Par exemple :
php_value upload_max_filesize 50M
php_value max_execution_time 240Pages d'erreur personnalisées
ErrorDocument 500 "Houston, on a un problème."
ErrorDocument 401 http://error.votredomaine.com/mordor.html
ErrorDocument 404 /errors/halflife3.htmlForcer le téléchargement
Parfois, vous souhaitez forcer le navigateur à télécharger certaines ressources
au lieu de les afficher. Le snippet suivant vous sera utile :
<Files *.md>
ForceType application/octet-stream
Header set Content-Disposition attachment
</Files>Si vous souhaitez l'action inverse :
Empêcher le téléchargement
Parfois, vous souhaitez forcer le navigateur à afficher certains contenus au
lieu de les télécharger. Le snippet suivant devrait vous aider :
<FilesMatch "\.(tex|log|aux)$">
Header set Content-Type text/plain
</FilesMatch>Autoriser les polices Cross-Domain
Les polices desservies par un serveur CDN peuvent ne pas fonctionner sur Firefox
ou IE à cause de
CORS. Le snippet
suivant de alrra
devrait corriger cela :
<IfModule mod_headers.c>
<FilesMatch "\.(eot|otf|ttc|ttf|woff|woff2)$">
Header set Access-Control-Allow-Origin "*"
</FilesMatch>
</IfModule>Encodage UTF-8 automatique
Votre contenu textuel devrait toujours être encodé en UTF-8, non ?
# Utiliser l'encodage UTF-8 pour tout ce qui est servi en text/plain ou text/html
AddDefaultCharset utf-8
# Forcer l'UTF-8 pour certains formats de fichier
AddCharset utf-8 .atom .css .js .json .rss .vtt .xmlBasculer vers une autre version de PHP
Si vous êtes sur un serveur mutualisé, il y a des chances pour qu'il y ait plus
d'une version de PHP installée, et parfois, vous avez besoin d'une version
spécifique pour votre site web.
Par exemple Laravel nécessite PHP >= 5.4.
Le snippet suivant devrait passer d'une version à l'autre de PHP pour vous :
AddHandler application/x-httpd-php55 .php
# Autrement, vous pouvez utiliser AddType
AddType application/x-httpd-php55 .phpDésactiver le mode de compatibilité pour Internet Explorer
Le mode de compatibilité dans IE peut affecter l'affichage de certains sites
web. L'extrait suivant devrait forcer IE à utiliser le moteur d'interprétation
Edge et ainsi désactiver le mode de compatibilité.
<IfModule mod_headers.c>
BrowserMatch MSIE is-msie
Header set X-UA-Compatible IE=edge env=is-msie
</IfModule>Servir des images WebP
Si WebP images est supporté
et que l'image avec l'extension .webp a le même nom qu'une image jpg/png alors
l'image Webp sera servie à la place.
RewriteEngine On
RewriteCond %{HTTP_ACCEPT} image/webp
RewriteCond %{DOCUMENT_ROOT}/$1.webp -f
RewriteRule (.+)\.(jpe?g|png)$ $1.webp [T=image/webp,E=accept:1]Overview (`Translations/German/README.md`)
.htaccess-Ausschnitte
Eine Sammlung nützlicher .htaccess-Ausschnitte, alle an einem Ort.
Haftungsausschluss: Während das Einfügen der Ausschnitte in eine .htaccess-Datei sehr zeitsparend ist, gibt es Fälle, in denen bestimme Veränderungen nötig sein könnten. Die Benutzung der Ausschnitte erfolgt auf eigene Gefahr.
WICHTIG: Apache 2.4 führt einige Änderungen ein, welche die Konfiguration zerstören könnten, hauptsächlich im Bereich der Zugangskontrolle. Für mehr Informationen sehen Sie sich das "Upgrading"-Dokument und dieses Ticket an.
Danksagungen
Wir sammeln hier hauptsächlich nützliche Ausschnitte aus dem Internet (beispielsweise aus Apache Server Configs) an einem Ort. Obwohl wir versuchen, alle Autoren zu erwähnen, ist es möglich, dass einige vergessen wurden. Sollten Sie glauben, dass etwas hiervon Ihre Arbeit ist und Sie erwähnt werden sollten, lassen Sie uns dies wissen oder erstellen Sie einfach eine Pull-Anfrage.
Inhalt
- Umschreibung und Weiterleitung
- www erzwingen
- www allgemein erzwingen
- nicht-www erzwingen
- nicht-www allgemein erzwingen
- HTTPS erzwingen
- HTTPS hinter einem Proxy erzwingen
- Abschließende Querstriche erzwingen
- Abschließende Querstriche entfernen
- Eine einzelne Seite weiterleiten
- Alias für ein einzelnes Verzeichnis hinzufügen
- Verzeichnisalias für ein Skript hinzufügen
- Eine komplette Seite weiterleiten
- Alias für "saubere" URLs hinzufügen
- Sicherheit
- Kompletten Zugriff verbieten
- Kompletten Zugriff außer Ihren verbieten
- Zugriff erlauben, außer von Spammern
- Zugriff zu versteckten Dateien und Verzeichnissen verbieten
- Zugriff zu Backup- und Quelldateien verbieten
- Verzeichnis-Auflistung abschalten
- Bild-Hotlinking abschalten
- Bild-Hotlinking für spezielle Domains abschalten
- Ein Verzeichnis mit Passwort schützen
- Eine oder mehrere Dateien mit Passwort schützen
- Besucher nach Referrer blockieren
- Verbieten, die Seite in Frames zu verwenden
- Leistung
- Verschiedenes
Umschreibung und Weiterleitung
Anmerkung: Es wird vorausgesetzt, dass Sie mod_rewrite installiert und aktiviert haben.
www erzwingen
RewriteEngine on
RewriteCond %{HTTP_HOST} ^example\.com [NC]
RewriteRule ^(.*)$ http://www.example.com/$1 [L,R=301,NC]www allgemein erzwingen
RewriteCond %{HTTP_HOST} !^$
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTPS}s ^on(s)|
RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]Dies funktioniert für jede Domain. Quelle
nicht-www erzwingen
Es wird noch immer diskutiert, ob www oder nicht-www besser ist, wenn Sie also ein Fan von knappen Domains sind:
RewriteEngine on
RewriteCond %{HTTP_HOST} ^www\.example\.com [NC]
RewriteRule ^(.*)$ http://example.com/$1 [L,R=301]nicht-www allgemein erzwingen
RewriteEngine on
RewriteCond %{HTTP_HOST} ^www\.
RewriteCond %{HTTPS}s ^on(s)|off
RewriteCond http%1://%{HTTP_HOST} ^(https?://)(www\.)?(.+)$
RewriteRule ^ %1%3%{REQUEST_URI} [R=301,L]HTTPS erzwingen
RewriteEngine on
RewriteCond %{HTTPS} !on
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}
# Bemerkung: Es wird außerdem empfohlen, HTTP Strict Transport Security (HSTS)
# auf Ihrer HTTPS-Webseite zu aktivieren, um Man-in-the-Middle-Attacken zu vermeiden.
# Siehe https://developer.mozilla.org/en-US/docs/Web/Security/HTTP_strict_transport_security
<IfModule mod_headers.c>
Header always set Strict-Transport-Security "max-age=31536000; includeSubDomains"
</IfModule>HTTPS hinter einem Proxy erzwingen
Nützlich, wenn Sie einen Proxy vor Ihrem Server haben, der TLS-Termination ausführt.
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}Abschließende Querstriche erzwingen
RewriteCond %{REQUEST_URI} /+[^\.]+$
RewriteRule ^(.+[^/])$ %{REQUEST_URI}/ [R=301,L]Abschließende Querstriche entfernen
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$ /$1 [R=301,L]Eine einzelne Seite weiterleiten
Redirect 301 /oldpage.html http://www.example.com/newpage.html
Redirect 301 /oldpage2.html http://www.example.com/folder/Alias für ein einzelnes Verzeichnis hinzufügen
RewriteEngine On
RewriteRule ^source-directory/(.*) target-directory/$1Verzeichnisalias für ein Skript hinzufügen
FallbackResource /index.fcgiIn diesem Beispiel ist eine index.fcgi-Datei in einem Verzeichnis vorhanden und alle Anfragen in dieses Verzeichnis, die keinem vorhandenen Datei- oder Verzeichnisnamen zugewiesen werden können, werden stattdessen an das index.fcgi-Skript gesendet. Dies ist nützlich, wenn Sie möchten, dass baz.foo/index.fcgi (was auch Anfragen an baz.foo bearbeitet) von baz.foo/some/cool/path aufgerufen wird, während baz.foo/css/style.css und ähnliche Dateien weiterhin funktionieren. Sie können über die Umgebungsvariable PATH_INFO, die von Ihrer Skriptingumgebung zur Verfügung gestellt wird, auf den ursprünglichen Pfad zugreifen.
RewriteEngine On
RewriteRule ^$ index.fcgi/ [QSA,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.fcgi/$1 [QSA,L]Dies ist eine weniger effiziente Variante der FallbackResource-Direktive (da die Verwendung von mod_rewrite komplexer ist, als einfach nur die FallbackResource-Direktive zu nutzen), allerdings ist sie auch flexibler.
Eine komplette Seite weiterleiten
Redirect 301 / http://newsite.com/Auf diese Art bleiben die Links intakt. www.oldsite.com/some/crazy/link.html wird zu www.newsite.com/some/crazy/link.html. Dies ist sehr hilfreich, wenn Sie eine Seite nur zu einer neuen Domain "umziehen". Quelle
Alias für "saubere" URLs hinzufügen
Dieser Ausschnitt erlaubt Ihnen, "saubere URLs", also URLs ohne Dateinamenserweiterung, beispielsweise example.com/users anstelle von example.com/users.php zu verwenden.
RewriteEngine On
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule ^([^.]+)$ $1.php [NC,L]Sicherheit
Kompletten Zugriff verbieten
## Apache 2.2
Deny from all
## Apache 2.4
# Require all deniedAchtung, dadurch werden alle Benutzer, auch Sie selbst, von der Webseite ausgesperrt.
Kompletten Zugriff außer Ihren verbieten
## Apache 2.2
Order deny,allow
Deny from all
Allow from xxx.xxx.xxx.xxx
## Apache 2.4
# Require all denied
# Require ip xxx.xxx.xxx.xxxxxx.xxx.xxx.xxx ist Ihre IP-Adresse. Wenn Sie die letzten drei Ziffern beispielsweise mit 0/12 ersetzen, geben Sie einen Bereich von IP-Adressen im selben Netzwerk an. Dadurch müssen Sie nicht alle erlaubten IP-Adressen aus einem Netzwerk separat auflisten. Quelle
Natürlich gibt es auch eine umgekehrte Version:
Zugriff erlauben, außer von Spammern
## Apache 2.2
Order deny,allow
Deny from xxx.xxx.xxx.xxx
Deny from xxx.xxx.xxx.xxy
## Apache 2.4
# Require all granted
# Require not ip xxx.xxx.xxx.xxx
# Require not ip xxx.xxx.xxx.xxyZugriff zu versteckten Dateien und Verzeichnissen verbieten
Versteckte Dateien und Verzeichnisse (die, deren Name mit einem Punkt . startet) sollen meistens, wenn nicht immer, abgesichert werden. Zum Beispiel: .htaccess, .htpasswd, .git, .hg...
RewriteCond %{SCRIPT_FILENAME} -d [OR]
RewriteCond %{SCRIPT_FILENAME} -f
RewriteRule "(^|/)\." - [F]Alternativ können Sie auch einen Not Found-Fehler ausgeben, damit der Angreifer keinen Hinweis auf die Existenz der Dateien erhält:
RedirectMatch 404 /\..*$Zugriff zu Backup- und Quelldateien verbieten
Diese Dateien können von manchen Editoren (wie Vi/Vim) zurückgelassen werden, und stellen ein großes Sicherheitsrisiko dar, wenn diese der Öffentlichkeit preisgegeben werden.
<FilesMatch "(\.(bak|config|dist|fla|inc|ini|log|psd|sh|sql|swp)|~)$">
## Apache 2.2
Order allow,deny
Deny from all
Satisfy All
## Apache 2.4
# Require all denied
</FilesMatch>Verzeichnis-Auflistung abschalten
Options All -IndexesBild-Hotlinking abschalten
RewriteEngine on
# Entfernen Sie die folgende Zeile, wenn Sie auch Anfragen mit leerem Referrer blockieren möchten
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http(s)?://(.+\.)?example.com [NC]
RewriteRule \.(jpg|jpeg|png|gif|bmp)$ - [NC,F,L]
# Wenn Sie einen "Blockiert"-Banner anstatt des gehotlinkten Bildes
# anzeigen möchten, ersetzen Sie die obere Regel mit:
# RewriteRule \.(jpg|jpeg|png|gif|bmp) http://example.com/blocked.png [R,L]Bild-Hotlinking für spezielle Domains abschalten
Manchmal möchte man Bild-Hotlinking nur für manche Seiten deaktivieren.
RewriteEngine on
RewriteCond %{HTTP_REFERER} ^http(s)?://(.+\.)?badsite\.com [NC,OR]
RewriteCond %{HTTP_REFERER} ^http(s)?://(.+\.)?badsite2\.com [NC,OR]
RewriteRule \.(jpg|jpeg|png|gif)$ - [NC,F,L]
# Wenn Sie einen "Blockiert"-Banner anstatt des gehotlinkten Bildes
# anzeigen möchten, ersetzen Sie die obere Regel mit:
# RewriteRule \.(jpg|jpeg|png|gif|bmp) http://example.com/blocked.png [R,L]Ein Verzeichnis mit Passwort schützen
Zuerst müssen Sie irgendwo eine .htpasswd-Datei erstellen:
htpasswd -c /home/fellowship/.htpasswd boromirDann können Sie diese zur Authentifizierung benutzen:
AuthType Basic
AuthName "One does not simply"
AuthUserFile /home/fellowship/.htpasswd
Require valid-userEine oder mehrere Dateien mit Passwort schützen
AuthName "One still does not simply"
AuthType Basic
AuthUserFile /home/fellowship/.htpasswd
<Files "one-ring.o">
Require valid-user
</Files>
<FilesMatch ^((one|two|three)-rings?\.o)$>
Require valid-user
</FilesMatch>Besucher nach Referrer blockieren
Verbietet den Zugriff für alle Benutzer, die von einer bestimmten Domain weitergeleitet wurden.
Quelle
RewriteEngine on
# Options +FollowSymlinks
RewriteCond %{HTTP_REFERER} somedomain\.com [NC,OR]
RewriteCond %{HTTP_REFERER} anotherdomain\.com
RewriteRule .* - [F]Verbieten, die Seite in Frames zu verwenden
Dies schützt die Webseite davor, in einem Frame (z.B. einem iframe) dargestellt zu werden, wobei eine bestimmte URI immer noch in einen Frame eingebettet werden darf.
SetEnvIf Request_URI "/starry-night" allow_framing=true
Header set X-Frame-Options SAMEORIGIN env=!allow_framingLeistung
Textdateien komprimieren
/* Detailed source-code truncated for AI context efficiency. */Ablaufdatum im Header setzen
Expire headers (Ablauf-Header) teilen dem Browser mit, ob er eine bestimmte Datei vom Server oder aus dem Cache laden soll. Es ist ratsam, das Ablaufdatum von statischen Inhalten weit in die Zukunft zu legen.
Wenn Sie die Versionierung nicht durch Dateinamen kontrollieren, ziehen Sie in Betracht, die Cachezeit für Ressourcen wie CSS und JS auf ca. eine Woche zu verringern. Quelle
/* Detailed source-code truncated for AI context efficiency. */eTags abschalten
Durch das Entfernen des ETag-Headers können Sie Caches und Browser davon abhalten, die Dateien zu validieren, sodass sie von Ihren Cache-Control und Expires-Headern abhängig sind. Quelle
<IfModule mod_headers.c>
Header unset ETag
</IfModule>
FileETag NoneVerschiedenes
PHP-Variablen setzen
php_value <key> <val>
# Zum Beispiel:
php_value upload_max_filesize 50M
php_value max_execution_time 240Eigene Fehlerseiten
ErrorDocument 500 "Houston, wir haben ein Problem."
ErrorDocument 401 http://error.example.com/mordor.html
ErrorDocument 404 /errors/halflife3.htmlDownload erzwingen
Manchmal möchten Sie den Browser dazu zwingen, Inhalte herunterzuladen, anstatt sie nur anzuzeigen.
<Files *.md>
ForceType application/octet-stream
Header set Content-Disposition attachment
</Files>Es gibt auch ein Yang zu diesem Yin:
Download verhindern
Manchmal möchten Sie den Browser dazu zwingen, Inhalte nur anzuzeigen, anstatt sie herunterzuladen.
<FilesMatch "\.(tex|log|aux)$">
Header set Content-Type text/plain
</FilesMatch>Domainübergreifende Schriftarten erlauben
Web-Schriftarten von CDNs funktionieren möglicherweise nicht in Firefox oder IE (siehe CORS). Dieser Ausschnitt löst dieses Problem.
<IfModule mod_headers.c>
<FilesMatch "\.(eot|otf|ttc|ttf|woff|woff2)$">
Header set Access-Control-Allow-Origin "*"
</FilesMatch>
</IfModule>Automatische UTF-8-Kodierung
Häufig ist es wünschenswert, dass Text immer als UTF-8 kodiert wird.
# UTF-8-Kodierung für alles verwenden, was als text/plain oder text/html angeboten wird
AddDefaultCharset utf-8
# UTF-8-Kodierung für bestimmte Dateitypen erzwingen
AddCharset utf-8 .atom .css .js .json .rss .vtt .xmlZu einer anderen PHP-Version wechseln
Auf einem von mehreren Personen genutzten Server ist häufig mehr als eine PHP-Version installiert, Sie möchten aber möglicherweise eine bestimmte Version für Ihre Webseite nutzen. Beispielsweise benötigt Laravel PHP >= 5.4. Der folgende Ausschnitt sollte die PHP-Version für Sie wechseln.
AddHandler application/x-httpd-php55 .php
# Alternativ können Sie AddType benutzen
AddType application/x-httpd-php55 .phpKompatibilitätsansicht des Internet Explorer deaktivieren
Die Kompatibilitätsansicht des IE kann sich darauf auswirken, wie manche Webseiten dargestellt werden. Der folgende Ausschnitt sollte IE dazu zwingen, die Edge Rendering Engine zu benutzen und die Kompatibilitätsansicht zu deaktivieren.
<IfModule mod_headers.c>
BrowserMatch MSIE is-msie
Header set X-UA-Compatible IE=edge env=is-msie
</IfModule>WebP-Bilder bereitstellen
Wenn WebP-Bilder unterstützt werden und ein Bild mit der Dateinamenserweiterung .webp mit demselben Namen und am selben Ort wie ein jpg/png-Bild, gefunden wird, dann wird das WebP-Bild anstelle des jpg/png-Bildes angezeigt.
RewriteEngine On
RewriteCond %{HTTP_ACCEPT} image/webp
RewriteCond %{DOCUMENT_ROOT}/$1.webp -f
RewriteRule (.+)\.(jpe?g|png)$ $1.webp [T=image/webp,E=accept:1]Overview (`Translations/Italian/README.md`)
.htaccess Snippets [](https://github.com/sindresorhus/awesome)
Una collezione di esempi utili di .htaccess.
Disclaimer: Anche se nella maggior parte dei casi basta copiare l'.htaccess d'esempio ci sono casi in cui sia necessario fare delle modifiche. L'utilizzo è a vostro totale rischio.
IMPORTANTE: Apache 2.4 introduce alcuni cambiamenti, in particolare la configurazione del controllo degli accessi. Per maggiori informazioni potete consultare il documento sull'aggiornamento oltre a questa problematica.
Riconoscimenti
Ciò che stiamo facendo è mettere insieme esempi utili da tutto il web (ad esempio, una buona parte viene da Apache Server Configs) in un solo posto. Anche se abbiamo cercato di dare riconoscimento, dove previsto, potrebbe mancare qualche riferimento. Se credete che sia presente del vostro lavoro e volete che venga riconosciuto fatecelo sapere e inviateci un PR.
Sommario
- Rewrite e Redirection
- Forza www
- Forza www in maniera generica
- Forza non-www
- Forza non-www in maniera generica
- Forza HTTPS
- Forza HTTPS se dietro Proxy
- Forza lo Slash finale
- Rimuovi lo Slash finale
- Rimuovi lo Slash finale da percorsi arbitrari
- Redireziona una singola pagina
- Alias a singole Cartelle
- Percorsi Alias a Script
- Redireziona un Intero Sito
- Alias per URL "Pulite"
- Sicurezza
- Nega tutti gli accessi
- Nega l'accesso a tutti tranne per te stesso
- Permetti a tutti l'accesso tranne agli Spammer
- Nega l'accesso a Cartelle e File Nascosti
- Nega l'accesso a Backup e File Sorgenti
- Disabilita l'Esplorazione delle Cartelle
- Disabilita Hotlinking delle Immagini
- Disabilita Hotlinking delle Immagini per Domini Specifici
- Proteggi una Cartella con Password
- Proteggi uno o più file con Password
- Blocca i visitatori in base al Referrer
- Previeni l'inclusione del Sito tramite frame (framing)
- Prestazioni
- Miscellanea
- Imposta variabili PHP
- Pagine di Errore Personalizzate
- Forza il Download
- Previeni il Download
- Permetti i Web Font da domini differenti
- Codifica automaticamente in UTF-8
- Passa a una versione diversa di PHP
- Disabilita Visualizzazione Compatibilità di Internet Explorer
- Rendere disponibili immagini in formato WebP
Rewrite e Redirection
Nota: Si presume che mod_rewrite sia installato e abilitato.
Forza www
RewriteEngine on
RewriteCond %{HTTP_HOST} ^esempio\.com [NC]
RewriteRule ^(.*)$ http://www.esempio.com/$1 [L,R=301,NC]Forza www in maniera generica
RewriteCond %{HTTP_HOST} !^$
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTPS}s ^on(s)|
RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]Funziona per qualsiasi dominio. Sorgente
Forza non-www
E' ancora aperta la discussione sul se utilizzare o meno www. Se invece preferite domini senza www:
RewriteEngine on
RewriteCond %{HTTP_HOST} ^www\.esempio\.com [NC]
RewriteRule ^(.*)$ http://esempio.com/$1 [L,R=301]Forza non-www in maniera generica
RewriteEngine on
RewriteCond %{HTTP_HOST} ^www\.
RewriteCond %{HTTPS}s ^on(s)|off
RewriteCond http%1://%{HTTP_HOST} ^(https?://)(www\.)?(.+)$
RewriteRule ^ %1%3%{REQUEST_URI} [R=301,L]Forza HTTPS
RewriteEngine on
RewriteCond %{HTTPS} !on
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}
# Nota: Si consiglia di abilitare anche HTTP Strict Transport Security (HSTS)
# sul sito HTTPS per aiutare a prevenire attacchi man-in-the-middle.
# Vedere https://developer.mozilla.org/en-US/docs/Web/Security/HTTP_strict_transport_security
<IfModule mod_headers.c>
Header always set Strict-Transport-Security "max-age=31536000; includeSubDomains"
</IfModule>Forza HTTPS se dietro Proxy
Utile se hai un proxy con TLS prima del tuo server.
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}Forza Slash Finale
RewriteCond %{REQUEST_URI} /+[^\.]+$
RewriteRule ^(.+[^/])$ %{REQUEST_URI}/ [R=301,L]Rimuovi Slash Finale
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$ /$1 [R=301,L]Rimuovi Slash Finale da percorsi arbitrari
Questo esempio redirezionerà i percorsi che finiscono con gli slash ai rispettivi percorsi senza slash (eccetto le attuali cartelle), es. http://www.esempio.com/blog/ in http://www.esempio.com/blog. E' importante per il SEO in quanto raccomandato per avere un URL canonico per ogni pagina.
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} (.+)/$
RewriteRule ^ %1 [L,R=301]Redireziona una singola pagina
Redirect 301 /vecchiapagina.html http://www.esempio.com/nuovapagina.html
Redirect 301 /vecchiapagina2.html http://www.esempio.com/cartella/Alias di una singola Cartella
RewriteEngine On
RewriteRule ^source-directory/(.*) /target-directory/$1 [R=301,L]Percorsi Alias a Script
FallbackResource /index.fcgiQuesto esempio presenta un file index.fcgi in alcune cartelle e ogni richiesta fallita nel risolvere un file/cartella verrà inviata allo script index.fcgi. Va bene se volete che baz.foo/some/cool/path venga gestito da baz.foo/index.fcgi (che supporta anche richieste verso baz.foo) mantenendo baz.foo/css/style.css e simili. Accedi al percorso originale dalla variabile d'ambiente PATH_INFO come previsto dal vostro ambiente di scripting.
RewriteEngine On
RewriteRule ^$ index.fcgi/ [QSA,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.fcgi/$1 [QSA,L]Questa è una versione meno efficiente della direttiva FallbackResource directive (l'uso di mod_rewrite è più complesso del gestire la direttiva FallbackResource) ma è anche più flessibile.
Redireziona un intero sito
Redirect 301 / http://nuovosito.com/Questo metodo ti permette di mantenere i collegamenti intatti. Il vecchio indirizzo www.vecchiosito.com/some/crazy/link.html diventerà www.nuovosito.com/some/crazy/link.html. E' estremamente utile quando ci si "sposta" verso un nuovo dominio. Sorgente
Alias per URL "Pulite"
Questo esempio ti permette di utilizzare URL "pulite" -- URL senza estensione PHP. es. esempio.com/utenti invece di esempio.com/utenti.php.
RewriteEngine On
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule ^([^.]+)$ $1.php [NC,L]Sicurezza
Nega tutti gli Accessi
## Apache 2.2
Deny from all
## Apache 2.4
# Require all deniedIn questa maniera rimarrai escluso anche tu dai tui contenuti! Per questo introduciamo...
Nega l'accesso a tutti tranne per te stesso
## Apache 2.2
Order deny,allow
Deny from all
Allow from xxx.xxx.xxx.xxx
## Apache 2.4
# Require all denied
# Require ip xxx.xxx.xxx.xxxxxx.xxx.xxx.xxx indica il tuo indirizzo IP. Se modifichi le ultime tre cifre con, per esempio, 0/12 verrà specificato un intervallo di IP all'interno della stessa rete, utile per non dover inserire singolarmente tutti gli ip. Sorgente
Ecco la versione al contrario:
Permetti a tutti gli accessi tranne agli Spammer
## Apache 2.2
Order deny,allow
Deny from xxx.xxx.xxx.xxx
Deny from xxx.xxx.xxx.xxy
## Apache 2.4
# Require all granted
# Require not ip xxx.xxx.xxx.xxx
# Require not ip xxx.xxx.xxx.xxyNega l'accesso a Cartelle e File Nascosti
La maggior parte, se non tutti, cartelle e File nascosti (quelli con i nomi che iniziano con il punto .) dovrebbero essere al sicuro. Per esempio: .htaccess, .htpasswd, .git, .hg...
RewriteCond %{SCRIPT_FILENAME} -d [OR]
RewriteCond %{SCRIPT_FILENAME} -f
RewriteRule "(^|/)\." - [F]In alternativa puoi inviare il messaggio "Not Found" error, giving the attacker dude no clue:
RedirectMatch 404 /\..*$Nega l'accesso a Backup e File Sorgenti
Questi file potrebbero esser stati lasciati da editor di testo o html (come Vi/Vim) e sono un possibile pericolo di sicurezza se mostrati al pubblico.
<FilesMatch "(\.(bak|config|dist|fla|inc|ini|log|psd|sh|sql|swp)|~)$">
## Apache 2.2
Order allow,deny
Deny from all
Satisfy All
## Apache 2.4
# Require all denied
</FilesMatch>Disabilita Esplorazione Cartella
Options All -IndexesDisabilita Hotlinking delle Immagini
RewriteEngine on
# Rimuovere la riga che segue se vuoi bloccare anche i referrer vuoti
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^https?://(.+\.)?esempio.com [NC]
RewriteRule \.(jpe?g|png|gif|bmp)$ - [NC,F,L]
# Se vuoi mostrare un banner di "blocco" al posto dell'immagine collegata (hotlinked),
# sostituisci la regola precedente con:
# RewriteRule \.(jpe?g|png|gif|bmp) http://esempio.com/blocked.png [R,L]Disabilita Hotlinking delle Immagini per Domini Specifici
A volte vuoi disabilitare il collegamento ad immagini del tuo sito (hotlinking) solo da alcuni cattivoni.
RewriteEngine on
RewriteCond %{HTTP_REFERER} ^https?://(.+\.)?badsite\.com [NC,OR]
RewriteCond %{HTTP_REFERER} ^https?://(.+\.)?badsite2\.com [NC,OR]
RewriteRule \.(jpe?g|png|gif|bmp)$ - [NC,F,L]
# Se vuoi mostrare un banner di "blocco" al posto dell'immagine collegata (hotlinked),
# sostituisci la regola precedente con:
# RewriteRule \.(jpe?g|png|gif|bmp) http://esempio.com/blocked.png [R,L]Proteggi una Cartella con Password
Prima è necessario creare un file .htpasswd da qualche parte nell sistema:
htpasswd -c /home/compagnia/.htpasswd boromirE adesso potete utilizzarlo per l'autenticazione:
AuthType Basic
AuthName "Non si entra con facilità"
AuthUserFile /home/compagnia/.htpasswd
Require valid-userProteggi uno o più file con Password
AuthName "Ancora non si entra con facilità"
AuthType Basic
AuthUserFile /home/compagnia/.htpasswd
<Files "one-ring.o">
Require valid-user
</Files>
<FilesMatch ^((one|two|three)-rings?\.o)$>
Require valid-user
</FilesMatch>Blocca i visitatori in base al Referrer
Nega l'accesso a tutti gli utenti che arrivano da (con referrer da) un dominio specifico.
Sorgente
RewriteEngine on
# Options +FollowSymlinks
RewriteCond %{HTTP_REFERER} undominio\.com [NC,OR]
RewriteCond %{HTTP_REFERER} unaltrodominio\.com
RewriteRule .* - [F]Previeni l'inclusione del Sito tramite frame (framing)
Previene la possibilità di inserimento del sito web tramite frame (es. inserito all'interno del tag iframe) permettendo solo un URI specifico.
SetEnvIf Request_URI "/starry-night" allow_framing=true
Header set X-Frame-Options SAMEORIGIN env=!allow_framingPrestazioni
Comprimi i File di Testo
/* Detailed source-code truncated for AI context efficiency. */Imposta gli Header "Expires"
Expires headers indicano al browser se devono richiedere il file al server o caricarli dalla cache. E' consigliabile impostare gli header expires per i contenuti statici con una data futura abbastanza ampia.
Se non controlli la versione del file in base al nome imposta la cache per risorse come CSS e JS a qualcosa come 1 settimana . Sorgente
/* Detailed source-code truncated for AI context efficiency. */Disabilita eTags
Rimuovendo l'intestazione ETag vegono disabilitate le cache del browser per poter validare i file e sono forzati a far fede alle intestazioni Cache-Control e Expires. Sorgente
<IfModule mod_headers.c>
Header unset ETag
</IfModule>
FileETag NoneMiscellanea
Set PHP Variables
php_value <key> <val>
# Peresempio:
php_value upload_max_filesize 50M
php_value max_execution_time 240Pagine Personalizzate di Errore
ErrorDocument 500 "Houston, abbiamo un problema."
ErrorDocument 401 http://errore.esempio.com/mordor.html
ErrorDocument 404 /errori/halflife3.htmlForza Download
A volte volete poter forzare il browser a scaricare una tipologia di contenuto al posto di mostrarlo.
<Files *.md>
ForceType application/octet-stream
Header set Content-Disposition attachment
</Files>Adesso c'è lo yang a questo yin:
Previeni il Download
A volte si vuole forzare il brower a mostrare una tipologia di contenuto al posto di farlo scaricare.
<FilesMatch "\.(tex|log|aux)$">
Header set Content-Type text/plain
</FilesMatch>Permetti i Web Font da domini differenti
I webfont messi a disposiziontra tramite CDN potrebbero non funzionare in Firefox o IE a causa dei CORS. Questo esempio risolve il problema.
<IfModule mod_headers.c>
<FilesMatch "\.(eot|otf|ttc|ttf|woff|woff2)$">
Header set Access-Control-Allow-Origin "*"
</FilesMatch>
</IfModule>Codifica automaticamente in UTF-8
Il contenuto del tuo testo de evessere sempre codificato UTF-8 no?
# Utilizza la codifica UTF-8 per qualasiasi contenuto inviato come text/plain or text/html
AddDefaultCharset utf-8
# Forza UTF-8 per un numero di formati file
AddCharset utf-8 .atom .css .js .json .rss .vtt .xmlPassa a un'altra versione di PHP Version
Se vi trovate in un hosting condiviso è possibile che sia presente più di una versione di PHP e a volte potreste aver bisogno di una versione specifica per il vostro sito web. Es. Laravel richiede PHP >= 5.4. il seguente esempio switch the PHP version for you.
AddHandler application/x-httpd-php55 .php
# Alternatively, you can use AddType
AddType application/x-httpd-php55 .phpDisabilita Visualizzazione Compatibilità di Internet Explorer
La Visualizzazione Compatibilità in internet exporer potrebbe creare problemi nel come vengano visualizzati alcuni siti web. Il seguente esempio dovrebbe forzare IE ad utilizzare il motore di Rendering Edge e disabilitare la Visualizzazione Compatibilità.
<IfModule mod_headers.c>
BrowserMatch MSIE is-msie
Header set X-UA-Compatible IE=edge env=is-msie
</IfModule>Rendere disponibili immagini in formato WebP
Se sono supportate le immagini WebP inviate un'immagine webp in caso sia stata richiesta un'immagine jpg/png con lo stesso nome e nello stesso percorso.
RewriteEngine On
RewriteCond %{HTTP_ACCEPT} image/webp
RewriteCond %{DOCUMENT_ROOT}/$1.webp -f
RewriteRule (.+)\.(jpe?g|png)$ $1.webp [T=image/webp,E=accept:1]Overview (`Translations/Japanese/README.md`)
.htaccess Snippets
.htaccessの便利なスニペットのまとめ
免責事項: スニペットを.htaccessで利用した場合、たいていは十分機能するはずですが、一定の修正が必要になることもあります。ご自身の責任で使用してください。
重要: Apache2.4ではいくつかの破壊的変更点があり、それはアクセスコントロールの設定において顕著です。より詳しい情報を知りたい場合は次のリンクをチェックしてください。 upgrading document こちらもどうぞ。 this issue.
クレジット
まとめている、便利なスニペットの大部分はインターネットを通じて収集されたものです。(例えば、かなりの部分は、Apache Server Configsからのものです)。Source等などを正確にクレジットしようと努めていますが、不足してることも考えられます。もしも、ご自分の制作物などがクレジットされるべきだという方がいれば私たちに知らせてください。
目次
URL書き換え&リダイレクト
注: mod_rewriteがインストールされていて有効になってることを前提とします。
wwwありに統一
RewriteEngine on
RewriteCond %{HTTP_HOST} ^example\.com [NC]
RewriteRule ^(.*)$ http://www.example.com/$1 [L,R=301,NC]wwwありに統一(包括的に)
RewriteCond %{HTTP_HOST} !^$
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTPS}s ^on(s)|
RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]上記の設定はどんなドメインでも動作します。 Source
wwwなしに統一
参考 still open for debate wwwのついたドメインかついてないドメインかは好きなほうにすればよいです。
RewriteEngine on
RewriteCond %{HTTP_HOST} ^www\.example\.com [NC]
RewriteRule ^(.*)$ http://example.com/$1 [L,R=301]wwwなしに統一(包括的に)
RewriteEngine on
RewriteCond %{HTTP_HOST} ^www\.
RewriteCond %{HTTPS}s ^on(s)|off
RewriteCond http%1://%{HTTP_HOST} ^(https?://)(www\.)?(.+)$
RewriteRule ^ %1%3%{REQUEST_URI} [R=301,L]httpsに統一
RewriteEngine on
RewriteCond %{HTTPS} !on
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}
# Note: It's also recommended to enable HTTP Strict Transport Security (HSTS)
# on your HTTPS website to help prevent man-in-the-middle attacks.
# See https://developer.mozilla.org/en-US/docs/Web/Security/HTTP_strict_transport_security
<IfModule mod_headers.c>
Header always set Strict-Transport-Security "max-age=31536000; includeSubDomains"
</IfModule>httpsに統一する(リバースプロキシー経由)
リバースプロキシーを経由してhttpsじゃなくなってるいる場合に便利です。
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}URL末尾をスラッシュ(/)で統一する
RewriteCond %{REQUEST_URI} /+[^\.]+$
RewriteRule ^(.+[^/])$ %{REQUEST_URI}/ [R=301,L]末尾のスラッシュ(/)を取り除く
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$ /$1 [R=301,L]決められたページにリダイレクトさせる
Redirect 301 /oldpage.html http://www.example.com/newpage.html
Redirect 301 /oldpage2.html http://www.example.com/folder/ディレクトリエイリアス設定
RewriteEngine On
RewriteRule ^source-directory/(.*) target-directory/$1スクリプトへのエイリアスパス
FallbackResource /index.fcgi存在しないディレクトリまたはファイルへのリクエストがあれば、スクリプト index.fcgi へ転送させるような時に使います。baz.foo/css/style.cssのような実際にファイルがある時はそちらにアクセスさせておいて、baz.foo/some/cool/pathのようなクールなURL表現で、baz.foo/index.fcgi (baz.fooへのリクエストでも同じく扱える)へリクエストを転送させるさせるような時に便利です。あなたのスクリプト環境にさらされるように、PATH_INFO環境変数から元のパスへのアクセスを取得します。
RewriteEngine On
RewriteRule ^$ index.fcgi/ [QSA,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.fcgi/$1 [QSA,L]上記の設定はFallbackResourceより非効率ですが(mod_rewriteはFallbackResourceを扱うより複雑なため)、より柔軟な設定が可能です。
とにかくリダイレクトする
Redirect 301 / http://newsite.com/この方法はそっくりそのまま別のサイトにリダイレクトさせます。www.oldsite.com/some/crazy/link.htmlにアクセスした場合、www.newsite.com/some/crazy/link.htmlにリダイレクトさせます。新しいドメインに引っ越したときなど、非常に役に立ちます。 Source
クリーンURLエイリアス
このスニペットは、クリーンURL用です。拡張子がPHPで、example.com/users.phpというURLをではなくexample.com/usersというURLとしてあつかえます。
RewriteEngine On
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule ^([^.]+)$ $1.php [NC,L]セキュリティ
全アクセス拒否
## Apache 2.2
Deny from all
## Apache 2.4
# Require all deniedあなたも同様にコンテンツをみれなくなるのでよく考えて利用してください。
特定のIPを除いたアクセスの拒否
## Apache 2.2
Order deny,allow
Deny from all
Allow from xxx.xxx.xxx.xxx
## Apache 2.4
# Require all denied
# Require ip xxx.xxx.xxx.xxxxxx.xxx.xxx.xxxはあなたのIPです。あなたが例えば12桁のIPのうち最後の3桁を0/12で交換する場合、同じネットワーク内のIPの範囲を指定することになり、別途許可IPを全てリストアップしなければいけないような面倒を回避します。
Source
もちろん逆のバージョンもあります。
特定のIPのみアクセスを拒否
## Apache 2.2
Order deny,allow
Allow from all
Deny from xxx.xxx.xxx.xxx
Deny from xxx.xxx.xxx.xxy
## Apache 2.4
# Require all granted
# Require not ip xxx.xxx.xxx.xxx
# Require not ip xxx.xxx.xxx.xxy隠しファイル、隠しディレクトリへのアクセス拒否
ドット.ではじまる隠しファイルや隠しディレクトリはいかなる時も安全である(閲覧されないようにする)必要があります。例えば、.htaccess, .htpasswd, .git, .hg 等です。
RewriteCond %{SCRIPT_FILENAME} -d [OR]
RewriteCond %{SCRIPT_FILENAME} -f
RewriteRule "(^|/)\." - [F]攻撃者に手がかりを与える代わりに、404エラーページを表示させることができます。
RedirectMatch 404 /\..*$バックアップファイルやソースファイルにアクセスするのを防ぐ
これらのファイルはviやvimによって置かれたり、公にさらされると、セキュリティ上の危険をもたらすファイルである可能性があります。
<FilesMatch "(\.(bak|config|dist|fla|inc|ini|log|psd|sh|sql|swp)|~)$">
## Apache 2.2
Order allow,deny
Deny from all
Satisfy All
## Apache 2.4
# Require all denied
</FilesMatch>ディレクトリ下のファイル一覧の表示禁止
Options All -Indexes画像直リンクの禁止
RewriteEngine on
# Remove the following line if you want to block blank referrer too
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^https?://(.+\.)?example.com [NC]
RewriteRule \.(jpe?g|png|gif|bmp)$ - [NC,F,L]
# もしも、直リンクされた画像の代わりにブロックしたことを示す画像を表示させたいのであれば
# `RewriteRule`を次のようにしてください:
# RewriteRule \.(jpe?g|png|gif|bmp) http://example.com/blocked.png [R,L]特定のドメインからの画像直リンクの禁止
特定のサイトからの画像直リンクを無効にしたい場合です。
RewriteEngine on
RewriteCond %{HTTP_REFERER} ^https?://(.+\.)?badsite\.com [NC,OR]
RewriteCond %{HTTP_REFERER} ^https?://(.+\.)?badsite2\.com [NC,OR]
RewriteRule \.(jpe?g|png|gif|bmp)$ - [NC,F,L]
# もしも、直リンクされた画像の代わりにブロック下ことを示す画像を表示させたいのであれば
# `RewriteRule`を次のようにしてください:
# RewriteRule \.(jpe?g|png|gif|bmp) http://example.com/blocked.png [R,L]ディレクトリをパスワードで保護する
最初に.htpasswd作成してシステムのどこかに配置しておく必要があります。
htpasswd -c /home/fellowship/.htpasswd boromirそして、作成した.htpasswdを認証のために使うことができます。
AuthType Basic
AuthName "One does not simply"
AuthUserFile /home/fellowship/.htpasswd
Require valid-user一つか複数かのファイルをパスワードで保護する
AuthName "One still does not simply"
AuthType Basic
AuthUserFile /home/fellowship/.htpasswd
<Files "one-ring.o">
Require valid-user
</Files>
<FilesMatch ^((one|two|three)-rings?\.o)$>
Require valid-user
</FilesMatch>特定の他所のサイトからアクセスをブロック
この設定は特定のドメインからのアクセスをブロックします
Source
RewriteEngine on
# Options +FollowSymlinks
RewriteCond %{HTTP_REFERER} somedomain\.com [NC,OR]
RewriteCond %{HTTP_REFERER} anotherdomain\.com
RewriteRule .* - [F]フレーミングされるのを防ぐ
下記の設定はウェブサイトがフレーム内に表示(IEではiframeを使う)されるのを防止しています。同時に特定のURIの時には許可しています。
SetEnvIf Request_URI "/starry-night" allow_framing=true
Header set X-Frame-Options SAMEORIGIN env=!allow_framingパフォーマンス
テキストファイルの圧縮
/* Detailed source-code truncated for AI context efficiency. */Expires(有効期限)ヘッダを設定する
ブラウザはexpires (有効期限)ヘッダをみてコンテンツをサーバーから取得すべきか、キャッシュから取得するかを判断します。静的コンテンツの有効期限はいくらか遠い未来に設定したほうがよいといえます。
/* Detailed source-code truncated for AI context efficiency. */Etagをオフにする
ETagヘッダを取り除くことによって、ブラウザ側が持っているキャッシュファイルと、サーバー側にある実ファイルの内容、更新日などが同じかどうか等の検証作業を無効にして、Cache-Control と Expires ヘッダを利用するようにします。
<IfModule mod_headers.c>
Header unset ETag
</IfModule>
FileETag Noneその他の項目
PHPの環境変数をセットする
php_value <key> <val>
# 例:
php_value upload_max_filesize 50M
php_value max_execution_time 240カスタムのエラーページ
ErrorDocument 500 "Houston, we have a problem."
ErrorDocument 401 http://error.example.com/mordor.html
ErrorDocument 404 /errors/halflife3.html強制ダウンロード
コンテンツをブラウザに表示させるのではなく、強制的にダウンロードさせたい場合は次のようにします。
<Files *.md>
ForceType application/octet-stream
Header set Content-Disposition attachment
</Files>Now there is a yang to this yin:
ダウンロードを防ぐ
コンテンツをダウンロードさせるのではなく内容をそのままブラウザに表示させたい時は次のようにします。
<FilesMatch "\.(tex|log|aux)$">
Header set Content-Type text/plain
</FilesMatch>WEBフォントに対する他のドメインからのアクセスを許可する
IE, Firefoxのだとクロスドメイン制約のため、WEBフォントが正常に機能しない可能性があります。CORS このスニペットはその問題を解決します。
<IfModule mod_headers.c>
<FilesMatch "\.(eot|otf|ttc|ttf|woff|woff2)$">
Header set Access-Control-Allow-Origin "*"
</FilesMatch>
</IfModule>自動的にUTF8エンコードにする
あなたのテキストコンテンツを常にUTF-8エンコードする時は次の設定をご利用ください。
# text/plain か text/htmlを配信する時はUTF-8を使用します。
AddDefaultCharset utf-8
# 特定のファイルフォーマットで強制的にUTF-8を使う
AddCharset utf-8 .atom .css .js .json .rss .vtt .xml別のPHPのバージョンに切り替える
もしも、あなたが共有のホストを利用している場合、おそらく複数のバージョンのPHPがインストールされている可能性があり、時には自分のウェブサイトで特定のバージョンのPHPを使いたくなるかもしれません。例えば、ララベルではPHP5.4以上である必要があります。次のスニペットを使えば自分のウェブサイト用のPHPバージョンに切り替える事ができます。
AddHandler application/x-httpd-php55 .php
# 代わりにAddTypeを使うこともできます。
AddType application/x-httpd-php55 .phpインターネットエクスプローラーの互換表示をさせない
IEの互換表示モードはIEにおけるウェブサイトの表示に影響があたえることがあります。次のスニペットを使用することで、IEに最新のエンジンでページをレンダリングさせて、互換表示をさせなくすることができます。
<IfModule mod_headers.c>
BrowserMatch MSIE is-msie
Header set X-UA-Compatible IE=edge env=is-msie
</IfModule>WebP画像の配信
もしも、WebP images がサポートされていて、同じでディレクトリ下に、同じ名前のファイル名で、.webp と jpg/pngの拡張子のファイルがあった場合、WebP画像(.webp)が優先して配信されます。
RewriteEngine On
RewriteCond %{HTTP_ACCEPT} image/webp
RewriteCond %{DOCUMENT_ROOT}/$1.webp -f
RewriteRule (.+)\.(jpe?g|png)$ $1.webp [T=image/webp,E=accept:1]Overview (`Translations/Portuguese-BR/README.md`)
.htaccess Snippets
Uma coleção de snippets .htaccess úteis, tudo em um só lugar.
Disclaimer: ao deixar cair o trecho em um arquivo .htaccess é a maior parte do tempo suficiente, há casos em que algumas modificações podem ser necessárias. Use por sua conta e risco.
IMPORTANTE: Apache 2.4 introduz algumas alterações significativas, principalmente na configuração de controle de acesso. Para mais informações, consulte o upgrading document bem como this issue.
Créditos
O que estamos fazendo aqui é principalmente a coleta trechos úteis de todo o interwebs (por exemplo, uma boa parte é de
Apache Server Configs) em um só lugar. Enquanto estamos tentando dar crédito onde, devido, as coisas podem estar em falta. Se você acreditar em qualquer coisa que está aqui deve ser dado o seu trabalho e créditos, avise-nos, ou apenas enviar uma PR.
Tabela de Conteúdo
- Rewrite and Redirection
- Security
- Deny All Access
- Deny All Access Except Yours
- Allow All Access Except Spammers'
- Deny Access to Hidden Files and Directories
- Deny Access to Backup and Source Files
- Disable Directory Browsing
- Disable Image Hotlinking
- Disable Image Hotlinking for Specific Domains
- Password Protect a Directory
- Password Protect a File or Several Files
- Block Visitors by Referrer
- Prevent Framing the Site
- Performance
- Miscellaneous
Rewrite and Redirection
Nota: Presume-se que você tem mod_rewrite instalado e habilitado.
Force www
RewriteEngine on
RewriteCond %{HTTP_HOST} ^example\.com [NC]
RewriteRule ^(.*)$ http://www.example.com/$1 [L,R=301,NC]Force www in a Generic Way
RewriteCond %{HTTP_HOST} !^$
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTPS}s ^on(s)|
RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]Isso funciona para any domain. Source
Force non-www
It's still open for debate se www ou non-www é o caminho a percorrer, por isso, se acontecer de você ser um fã de domínios descalços, aqui você vai:
RewriteEngine on
RewriteCond %{HTTP_HOST} ^www\.example\.com [NC]
RewriteRule ^(.*)$ http://example.com/$1 [L,R=301]Force non-www in a Generic Way
RewriteEngine on
RewriteCond %{HTTP_HOST} ^www\.
RewriteCond %{HTTPS}s ^on(s)|off
RewriteCond http%1://%{HTTP_HOST} ^(https?://)(www\.)?(.+)$
RewriteRule ^ %1%3%{REQUEST_URI} [R=301,L]Force HTTPS
RewriteEngine on
RewriteCond %{HTTPS} !on
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}
# Nota: Também é recomendável habilitar HTTP Strict Transport Segurança (HSTS)
# Em seu site HTTPS para ajudar a prevenir ataques man-in-the-middle.
# Veja https://developer.mozilla.org/en-US/docs/Web/Security/HTTP_strict_transport_security
<IfModule mod_headers.c>
Header sempre definido Strict-Transport-Security "max-age=31536000; includeSubDomains"
</IfModule>Force HTTPS Behind a Proxy
Útil se você tiver um proxy na frente do seu servidor a realização de terminação TLS.
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}Force Trailing Slash
RewriteCond %{REQUEST_URI} /+[^\.]+$
RewriteRule ^(.+[^/])$ %{REQUEST_URI}/ [R=301,L]Remove Trailing Slash
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$ /$1 [R=301,L]Redirect a Single Page
Redirect 301 /oldpage.html http://www.example.com/newpage.html
Redirect 301 /oldpage2.html http://www.example.com/folder/Alias a Single Directory
RewriteEngine On
RewriteRule ^source-directory/(.*) target-directory/$1Alias Paths to Script
FallbackResource /index.fcgiEste exemplo tem um arquivo index.fcgi em algum diretório, e todos os pedidos dentro desse diretório que não conseguem resolver um diretório / nome do arquivo será enviado para o script index.fcgi. É bom se você quer baz.foo / some / cool / path a ser feitos pelo baz.foo / index.fcgi (que também suporta pedidos de baz.foo), mantendo baz.foo/css/ style.css e semelhantes. Tenha acesso ao caminho original da variável de ambiente PATH_INFO, como exposto no seu ambiente de script.
RewriteEngine On
RewriteRule ^$ index.fcgi/ [QSA,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.fcgi/$1 [QSA,L]Esta é uma versão menos eficiente da directiva FallbackResource (porque o uso do mod_rewrite é mais complexa do que apenas lidar com o directiva FallbackResource), mas também é mais flexível.
Redirect an Entire Site
Redirect 301 / http://newsite.com/Desta forma, faz com links intactos. Ou seja www.oldsite.com/some/crazy/link.html se tornará www.newsite.com/some/crazy/link.html. Isto é extremamente útil quando você é apenas "moving" um site para um novo domínio. Source
Alias "Clean" URLs
Este trecho permite que você use "clean" URLs -- aqueles sem uma extensão do PHP, por exemplo example.com/users em vez de example.com/users.php.
RewriteEngine On
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule ^([^.]+)$ $1.php [NC,L]Security
Deny All Access
## Apache 2.2
Deny from all
## Apache 2.4
# Require all deniedMas espere, isso irá bloqueá-lo a partir do seu conteúdo, bem! Assim, a introdução de ...
Deny All Access Except Yours
## Apache 2.2
Order deny,allow
Deny from all
Allow from xxx.xxx.xxx.xxx
## Apache 2.4
# Require all denied
# Require ip xxx.xxx.xxx.xxxxxx.xxx.xxx.xxx é seu IP. Se você substituir os três últimos dígitos com 0/12 por exemplo, isso vai especificar um intervalo de IPs dentro da mesma rede, poupando-lhe o trabalho de listar todos os IPs autorizados separadamente. Source
Agora é claro que há uma versão invertida:
Allow All Access Except Spammers'
## Apache 2.2
Order deny,allow
Deny from xxx.xxx.xxx.xxx
Deny from xxx.xxx.xxx.xxy
## Apache 2.4
# Require all granted
# Require not ip xxx.xxx.xxx.xxx
# Require not ip xxx.xxx.xxx.xxyDeny Access to Hidden Files and Directories
Arquivos e diretórios ocultos (aqueles cujos nomes começam com um ponto .) deve maioria, se não todos, o tempo ser assegurado. por exemplo: .htaccess, .htpasswd, .git, .hg...
RewriteCond %{SCRIPT_FILENAME} -d [OR]
RewriteCond %{SCRIPT_FILENAME} -f
RewriteRule "(^|/)\." - [F]Alternativamente, você pode simplesmente levantar uma Not Found erro, dando a cara atacante nenhuma pista:
RedirectMatch 404 /\..*$Deny Access to Backup and Source Files
Esses arquivos podem ser deixados por alguns editores de texto / html (como Vi / Vim) e representam um grande perigo de segurança, se exposto a público.
<FilesMatch "(\.(bak|config|dist|fla|inc|ini|log|psd|sh|sql|swp)|~)$">
## Apache 2.2
Order allow,deny
Deny from all
Satisfy All
## Apache 2.4
# Require all denied
</FilesMatch>Disable Directory Browsing
Options All -IndexesDisable Image Hotlinking
RewriteEngine on
# Remova a seguinte linha se você deseja bloquear referrer em branco também
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^https?://(.+\.)?example.com [NC]
RewriteRule \.(jpe?g|png|gif|bmp)$ - [NC,F,L]
# Se você deseja exibir um banner "bloqueada" em lugar da imagem hotlink,
# Substituir a regra acima, com:
# RewriteRule \.(jpe?g|png|gif|bmp) http://example.com/blocked.png [R,L]Disable Image Hotlinking for Specific Domains
Às vezes você quer desabilitar imagem hotlinking de alguns bandidos só.
RewriteEngine on
RewriteCond %{HTTP_REFERER} ^https?://(.+\.)?badsite\.com [NC,OR]
RewriteCond %{HTTP_REFERER} ^https?://(.+\.)?badsite2\.com [NC,OR]
RewriteRule \.(jpe?g|png|gif|bmp)$ - [NC,F,L]
# Se você deseja exibir um banner "bloqueada" em lugar da imagem hotlink,
# Substituir a regra acima, com:
# RewriteRule \.(jpe?g|png|gif|bmp) http://example.com/blocked.png [R,L]Password Protect a Directory
Primeiro você precisa criar um arquivo .htpasswd em algum lugar do sistema:
htpasswd -c /home/fellowship/.htpasswd boromirEm seguida, você pode usá-lo para autenticação:
AuthType Basic
AuthName "One does not simply"
AuthUserFile /home/fellowship/.htpasswd
Require valid-userPassword Protect a File or Several Files
AuthName "One still does not simply"
AuthType Basic
AuthUserFile /home/fellowship/.htpasswd
<Files "one-ring.o">
Require valid-user
</Files>
<FilesMatch ^((one|two|three)-rings?\.o)$>
Require valid-user
</FilesMatch>Block Visitors by Referrer
Este nega o acesso para todos os usuários que estão vindo de (indicado por) um domínio específico.
Source
RewriteEngine on
# Options +FollowSymlinks
RewriteCond %{HTTP_REFERER} somedomain\.com [NC,OR]
RewriteCond %{HTTP_REFERER} anotherdomain\.com
RewriteRule .* - [F]Prevent Framing the Site
Isso impede que o site para ser enquadrado (ou seja, colocar em uma iframe tag), quando ainda permite o enquadramento para uma URI específica.
SetEnvIf Request_URI "/starry-night" allow_framing=true
Header set X-Frame-Options SAMEORIGIN env=!allow_framingPerformance
Compress Text Files
/* Detailed source-code truncated for AI context efficiency. */Set Expires Headers
Expira headers dizer ao navegador se eles devem solicitar um arquivo específico do servidor ou apenas agarrá-lo a partir do cache. É aconselhável definir um conteúdo estática que expira no futuro.
Se você não controlar o versionamento com cache baseado em filename, tem que considerar uma redução do tempo de cache para recursos como CSS e JS para algo como uma semana. Source
/* Detailed source-code truncated for AI context efficiency. */Turn eTags Off
Ao remover o cabeçalho ETag, você desativar caches e navegadores de ser capaz de validar os arquivos, então eles são forçados a confiar em seu Cache-Control e cabeçalho Expires. Source
<IfModule mod_headers.c>
Header unset ETag
</IfModule>
FileETag NoneMiscellaneous
Set PHP Variables
php_value <key> <val>
# Por exemplo:
php_value upload_max_filesize 50M
php_value max_execution_time 240Custom Error Pages
ErrorDocument 500 "Houston, você tem um problema."
ErrorDocument 401 http://error.example.com/mordor.html
ErrorDocument 404 /errors/halflife3.htmlForce Downloading
Às vezes você quer forçar o navegador para baixar algum conteúdo em vez de exibi-lo.
<Files *.md>
ForceType application/octet-stream
Header set Content-Disposition attachment
</Files>Agora a um yang a este yin:
Prevent Downloading
Às vezes você quer forçar o navegador para exibir algum conteúdo em vez de baixá-lo.
<FilesMatch "\.(tex|log|aux)$">
Header set Content-Type text/plain
</FilesMatch>Allow Cross-Domain Fonts
CDN-served webfonts pode não funcionar no Firefox ou IE devido à CORS. Este trecho resolve o problema.
<IfModule mod_headers.c>
<FilesMatch "\.(eot|otf|ttc|ttf|woff|woff2)$">
Header set Access-Control-Allow-Origin "*"
</FilesMatch>
</IfModule>Auto UTF-8 Encode
Seu texto deve ser sempre codificação UTF-8, não?
# Use codificação UTF-8 para qualquer coisa como text/plain ou text/html
AddDefaultCharset utf-8
# Força UTF-8 para um número de formatos de arquivo
AddCharset utf-8 .atom .css .js .json .rss .vtt .xmlSwitch to Another PHP Version
Se você estiver em um servidor compartilhado, as chances são de que há mais de uma versão do PHP instalado, e às vezes você quer uma versão específica para o seu site. por exemplo, Laravel requer PHP >= 5.4. O seguinte trecho deve mudar a versão do PHP para você.
AddHandler application/x-httpd-php55 .php
# Alternativamente, você pode usar AddType
AddType application/x-httpd-php55 .phpDisable Internet Explorer Compatibility View
Exibição de Compatibilidade no IE pode afetar a forma como alguns sites são exibidos. O seguinte trecho deve forçar o IE para usar o Edge Rendering Engine e desativar o Compatibility View.
<IfModule mod_headers.c>
BrowserMatch MSIE is-msie
Header set X-UA-Compatible IE=edge env=is-msie
</IfModule>Serve WebP Images
Se WebP images são suportados em uma imagem com uma extensão .webp e ela encontra-se no mesmo lugar como o jpg/png imagem que vai ser servida, em seguida, a imagem WebP é servido em vez do jpg/png.
RewriteEngine On
RewriteCond %{HTTP_ACCEPT} image/webp
RewriteCond %{DOCUMENT_ROOT}/$1.webp -f
RewriteRule (.+)\.(jpe?g|png)$ $1.webp [T=image/webp,E=accept:1]Overview (`Translations/Russian/README.md`)
.htaccess сниппеты [](https://github.com/sindresorhus/awesome)
Коллекция .htaccess сниппетов, собранных в одном месте.
Дисклеймер: Перед тем, как использовать сниппет в файле .htaccess, в большинстве случаев необходимо сделать небольшие коррекции (поменять название папки или файла, изменить URL и т.д.). Используйте сниппеты на свой страх и риск.
ВАЖНО: В Apache 2.4 появилось несколько важных изменений, особенно в конфигурации управления доступами. Чтобы узнать больше об этих и других изменениях перейдите по этой ссылке, а также просмотрите это ишью.
Поддержка
Что мы делаем? Здесь собраны самые полезные сниппеты для файла .htaccess из всего интернета (например, много разных приемов из Apache Server Configs мы собрали в одном месте). Не исключено, что мы могли что-то упустить. Если вы заметили где-то ошибки или несоответствия, пожалуйста, сообщите нам об этом или сделайте Pull Request.
Подробнее о том, как помочь проекту и делать Pull Request'ы, вы можете прочитать в этой статье на Хабрахабр.
Содержание
- Rewrite и Redirect
- Перенаправление с без www на с www
- Перенаправление с без www на с www для HTTP или HTTPS
- Перенаправление с www на без www
- Перенаправление с www на без www для HTTP или HTTPS
- Принудительное использование HTTPS
- Принудительное использование HTTPS за прокси
- Вставить завершающий слэш
- Удалить завершающий слэш
- Редирект со страницы на страницу
- Редирект с использованием RedirectMatch
- Алиас для определенной директории
- Алиас пути до скрипта
- Редирект всего сайта
- Использовать чистые URL
- Безопасность
- Запретить доступ всем
- Запретить доступ всем, кроме...
- Разрешить доступ всем, кроме...
- Запретить доступ к скрытым файлам и директориям
- Запретить доступ к файлам
- Запретить листинг директорий
- Запретить хотлинкинг изображений
- Запретить хотлинкинг изображений для определенных доменов
- Защитить паролем директорию
- Защитить паролем один или несколько файлов
- Заблокировать посетителя по Referrer
- Запретить рендеринг сайта во фрейме
- Производительность
- Разное
- Настройка PHP
- Пользовательские страницы ошибок
- Принудительная загрузка (скачивать файл вместо отображения в браузере)
- Запретить загрузку (отображать plain в браузере)
- Разрешить кроссдоменные шрифты
- Установить по умолчанию кодировку UTF-8
- Переключиться на другую версию PHP
- Выключить режим совместимости в Internet Explorer
- Обработка WebP изображений
Rewrite и Redirect
Примечание: Предполагается, что модуль mod_rewrite установлен и включен.
Перенаправление с без www на с www
RewriteEngine on
RewriteCond %{HTTP_HOST} ^example\.com [NC]
RewriteRule ^(.*)$ http://www.example.com/$1 [L,R=301,NC]Перенаправление с без www на с www для HTTP или HTTPS
RewriteCond %{HTTP_HOST} !^$
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTPS}s ^on(s)|
RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]Это работает для любого домена. Источник
Перенаправление с www на без www
Это вечная тема для дискуссий - использовать или не использовать www, но если вы поклонник "чистых" доменов, то:
RewriteEngine on
RewriteCond %{HTTP_HOST} ^www\.example\.com [NC]
RewriteRule ^(.*)$ http://example.com/$1 [L,R=301]Перенаправление с www на без www для HTTP или HTTPS
RewriteEngine on
RewriteCond %{HTTP_HOST} ^www\.
RewriteCond %{HTTPS}s ^on(s)|off
RewriteCond http%1://%{HTTP_HOST} ^(https?://)(www\.)?(.+)$
RewriteRule ^ %1%3%{REQUEST_URI} [R=301,L]Принудительное использование HTTPS
RewriteEngine on
RewriteCond %{HTTPS} !on
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}
# Примечание: Рекомендуется включить HTTP Strict Transport Security (HSTS)
# на вашем HTTPS сайте для предотвращения атак посредника (man-in-the-middle).
# https://developer.mozilla.org/en-US/docs/Web/Security/HTTP_strict_transport_security
<IfModule mod_headers.c>
Header always set Strict-Transport-Security "max-age=31536000; includeSubDomains"
</IfModule>Принудительное использование HTTPS за прокси
Полезно, если вы имеете прокси перед вашим сервером для TLS.
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}Вставить завершающий слэш
RewriteCond %{REQUEST_URI} /+[^\.]+$
RewriteRule ^(.+[^/])$ %{REQUEST_URI}/ [R=301,L]Удалить завершающий слэш
Этот сниппет перенаправляет из пути, который заканчивается на слэш, на путь без завершающего слэша (кроме реальных директорий), например, из http://www.example.com/blog/ перенаправит на http://www.example.com/blog.
Это важно для SEO, так как рекомендуется, чтобы каждая страница имела канонический URL.
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} (.+)/$
RewriteRule ^ %1 [R=301,L]Редирект со страницы на страницу
Redirect 301 /oldpage.html http://www.example.com/newpage.html
Redirect 301 /oldpage2.html http://www.example.com/folder/Редирект с использованием RedirectMatch
RedirectMatch 301 /subdirectory(.*) http://www.newsite.com/newfolder/$1
RedirectMatch 301 ^/(.*).htm$ /$1.html
RedirectMatch 301 ^/200([0-9])/([^01])(.*)$ /$2$3
RedirectMatch 301 ^/category/(.*)$ /$1
RedirectMatch 301 ^/(.*)/htaccesselite-ultimate-htaccess-article.html(.*) /htaccess/htaccess.html
RedirectMatch 301 ^/(.*).html/1/(.*) /$1.html$2
RedirectMatch 301 ^/manual/(.*)$ http://www.php.net/manual/$1
RedirectMatch 301 ^/dreamweaver/(.*)$ /tools/$1
RedirectMatch 301 ^/z/(.*)$ http://static.askapache.com/$1Алиас для определенной директории
RewriteEngine On
RewriteRule ^source-directory/(.*) /target-directory/$1 [R=301,L]Алиас пути до скрипта
FallbackResource /index.fcgiВ этом примере приведён файл index.fcgi, который лежит в каталоге и все запросы к этому каталогу, которые потерпели неудачу из-за отсутствия файла/директории будут перенаправлены на скрипт index.fcgi. Это хорошо, если вы хотите, чтобы baz.foo/some/cool/path обрабатывался скриптом baz.foo/index.fcgi (который также поддерживает запросы на baz.foo) в тоже время поддерживается baz.foo/css/style.css и другое подобное. Узнать истинный путь можно из переменной окружения PATH_INFO, которая доступна в скриптах.
RewriteEngine On
RewriteRule ^$ index.fcgi/ [QSA,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.fcgi/$1 [QSA,L]Это менее эффективная версия директивы FallbackResource (поскольку использование mod_rewrite сложнее, чем просто обработка директивой FallbackResource), но также и более гибкое.
Редирект всего сайта
Redirect 301 / http://newsite.com/Этот сайт не "ломает" ссылки. Этот путь www.oldsite.com/some/crazy/link.html перенаправит вас на www.newsite.com/some/crazy/link.html. Это очень полезно, когда вы просто переносите сайт на новый домен. Источник
Использовать чистые URL
Этот сниппет позволяет использовать "чистые" URL -- без расширения .php, например, example.com/users вместо example.com/users.php.
RewriteEngine On
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule ^([^.]+)$ $1.php [NC,L]Безопасность
Запретить доступ всем
## Apache 2.2
Deny from all
## Apache 2.4
# Require all deniedПодождите-ка, этот сниппет заблокирует доступ к сайту даже для вас! Сейчас исправим это...
Запретить доступ всем, кроме...
## Apache 2.2
Order deny,allow
Deny from all
Allow from xxx.xxx.xxx.xxx
## Apache 2.4
# Require all denied
# Require ip xxx.xxx.xxx.xxxxxx.xxx.xxx.xxx - это ваш IP. Если вы замените последние три цифры, например, на 0/12, этим вы определите диапазон IP внутри этой сети и это оградит вас от проблемы перечислять по отдельности все разрешённые IP. Источник
И, естественно, противоположная функция к этой:
Разрешить доступ всем, кроме...
## Apache 2.2
Order deny,allow
Deny from xxx.xxx.xxx.xxx
Deny from xxx.xxx.xxx.xxy
## Apache 2.4
# Require all granted
# Require not ip xxx.xxx.xxx.xxx
# Require not ip xxx.xxx.xxx.xxyЗапретить доступ к скрытым файлам и директориям
Скрытые файлы и директории (те, чьи имена начинаются с точки .) должны в большинстве, если не все, быть недоступны для других. Например: .htaccess, .htpasswd, .git, .hg...
RewriteCond %{SCRIPT_FILENAME} -d [OR]
RewriteCond %{SCRIPT_FILENAME} -f
RewriteRule "(^|/)\." - [F]Как вариант, вы можете показывать ошибку Not Found (не найдено), чтобы не давать атакующему подсказку:
RedirectMatch 404 /\..*$Запретить доступ к файлам
Эти файлы могут быть оставлены некоторыми редакторами text/html (вроде Vi/Vim) и представляют огромную дыру в безопасности, если станут общедоступными.
<FilesMatch "(\.(bak|config|dist|fla|inc|ini|log|psd|sh|sql|swp)|~)$">
## Apache 2.2
Order allow,deny
Deny from all
Satisfy All
## Apache 2.4
# Require all denied
</FilesMatch>Запретить листинг директорий
Options All -IndexesЗапретить хотлинкинг изображений
RewriteEngine on
# Удалите эту строчку, если вы хотите заблокировать пользователя с пустым Referrer
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^https?://(.+\.)?example.com [NC]
RewriteRule \.(jpe?g|png|gif|bmp)$ - [NC,F,L]
# Если вы захотите отображать вместо заблокированного изображения свой баннер,
# то замените правило выше на это:
# RewriteRule \.(jpe?g|png|gif|bmp) http://example.com/blocked.png [R,L]Запретить хотлинкинг изображений для определенных доменов
Иногда вам потребуется запретить хотлинкинг только для некоторых доменов.
RewriteEngine on
RewriteCond %{HTTP_REFERER} ^https?://(.+\.)?badsite\.com [NC,OR]
RewriteCond %{HTTP_REFERER} ^https?://(.+\.)?badsite2\.com [NC,OR]
RewriteRule \.(jpe?g|png|gif|bmp)$ - [NC,F,L]
# Если вы захотите отображать вместо заблокированного изображения свой баннер,
# то замените правило выше на это:
# RewriteRule \.(jpe?g|png|gif|bmp) http://example.com/blocked.png [R,L]Защитить паролем директорию
Сначала нужно создать файл .htpasswd в определенной директории:
htpasswd -c /home/fellowship/.htpasswd ваш_суперсекретный_парольИ потом использовать этот файл для аутентификации:
AuthType Basic
AuthName "One does not simply"
AuthUserFile /home/fellowship/.htpasswd
Require valid-userЗащитить паролем один или несколько файлов
AuthName "One still does not simply"
AuthType Basic
AuthUserFile /home/fellowship/.htpasswd
<Files "one-ring.o">
Require valid-user
</Files>
<FilesMatch ^((one|two|three)-rings?\.o)$>
Require valid-user
</FilesMatch>Заблокировать посетителя по Referrer
Блокирует доступ для всех пользователей, которые пришли (были перенаправлены) из определенного домена(-ов).
Источник
RewriteEngine on
# Options +FollowSymlinks
RewriteCond %{HTTP_REFERER} somedomain\.com [NC,OR]
RewriteCond %{HTTP_REFERER} anotherdomain\.com
RewriteRule .* - [F]Запретить рендеринг сайта во фрейме
Этот сниппет запрещает отображение сайта во фрейме (например, в теге iframe), но разрешает отображение сайта во фрейме для определенных URI.
SetEnvIf Request_URI "/starry-night" allow_framing=true
Header set X-Frame-Options SAMEORIGIN env=!allow_framingПроизводительность
Сжатие текстовых файлов
/* Detailed source-code truncated for AI context efficiency. */Установить Expires Headers
Expires headers говорят браузеру, должен ли он загружать файл из сервера или же из кэша. Для статичного контента рекомендуется установить Expires заголовки на что-нибудь далекое в будущем.
Если вы не контролируете изменение версий с помощью перебора, основанного на файлах, подумайте о том, чтобы уменьшить время кэша для CSS и JS, например, до 1 недели. Источник
/* Detailed source-code truncated for AI context efficiency. */Выключить eTags
Удаляя заголовок ETag, вы выключаете кэш и избавляете возможности проверять браузером файлы, следовательно они будут полагаться на заголовки Cache-Control и Expires. Источник
<IfModule mod_headers.c>
Header unset ETag
</IfModule>
FileETag NoneРазное
Настройка PHP
php_value <key> <val>
# Например:
php_value upload_max_filesize 50M
php_value max_execution_time 240Пользовательские страницы ошибок
ErrorDocument 500 "Хьюстон, у нас проблемы."
ErrorDocument 401 http://error.example.com/mordor.html
ErrorDocument 404 /errors/halflife3.htmlПринудительная загрузка (скачивать файл вместо отображения в браузере)
Иногда нужно загрузить запрашиваемый файл, а не отображать его в браузере.
<Files *.md>
ForceType application/octet-stream
Header set Content-Disposition attachment
</Files>А ниже сниппет, который делает это с точностью до наоборот:
Запретить загрузку (отображать plain в браузере)
Иногда нужно отобразить запрашиваемый файл в браузере, а не загружать его.
<FilesMatch "\.(tex|log|aux)$">
Header set Content-Type text/plain
</FilesMatch>Разрешить кроссдоменные шрифты
Шрифты, которые хранятся на CDN серверах, могут не работать в Firefox и IE из-за CORS. Данный сниппет решает эту проблему.
<IfModule mod_headers.c>
<FilesMatch "\.(eot|otf|ttc|ttf|woff|woff2)$">
Header set Access-Control-Allow-Origin "*"
</FilesMatch>
</IfModule>Установить по умолчанию кодировку UTF-8
Ваш текстовый контент должен быть всегда закодирован в UTF-8, не так ли?
# Используйте кодировку UTF-8 для обработки text/plain или text/html
AddDefaultCharset utf-8
# Принудительное использование UTF-8 для различных файлов
AddCharset utf-8 .atom .css .js .json .rss .vtt .xmlПереключиться на другую версию PHP
Если вы используете шаред хостинг, вполне вероятно, что там установлено несколько версий PHP. Но вам нужна конкретная версия PHP для вашего веб-сайта. Этот сниппет должен переключить PHP версию.
AddHandler application/x-httpd-php56 .php
# В качестве альтернативы вы можете использовать AddType
AddType application/x-httpd-php56 .phpВыключить просмотр в режиме совместимости в Internet Explorer
Просмотр в режиме совместимости в IE может оказать влияние на то, как отображаются некоторые сайты. Этот сниппет заставляет IE использовать движок Edge Rendering и выключает просмотр в режиме совместимости.
<IfModule mod_headers.c>
BrowserMatch MSIE is-msie
Header set X-UA-Compatible IE=edge env=is-msie
</IfModule>Обработка WebP изображений
Если WebP изображения поддерживаюся и изображения с расширениями .webp и теми же именами найдены в том же месте, где и изображения jpg/png, которые нужно отправить, то тогда вместо них отправляются изображения WebP.
RewriteEngine On
RewriteCond %{HTTP_ACCEPT} image/webp
RewriteCond %{DOCUMENT_ROOT}/$1.webp -f
RewriteRule (.+)\.(jpe?g|png)$ $1.webp [T=image/webp,E=accept:1]Overview (`Translations/Slovak/README.md`)
.htaccess Ukážky kódov
Kolekcia užitočných .htaccess súborov, všetky na jednom mieste. Rozhodol som sa vytvoriť tento repozitár po tom, čo som bol znudený z Googlenia, keď som potreboval presmerovať moje nové stránky na www.
DISCLAIMER: Vložiť kus kódu je väčšinou postačujúce, avšak existujú prípady, kedy treba kód pozmeniť. Použitie na vlastné riziko.
POZNÁMKA: Apache 2.4 prináša niekoľko zmien, najme pre kontrolu prístupu. Pre viac informácii sa pozrite na upgrading document a tiež na this issue.
Tabuľka obsahu
- Prepisovanie a presmerovanie
- Bezpečnosť
- Zakázanie prístupu pre všetkých
- Zakázanie prístupu všetkým okrem vás
- Povoliť prístup všetkým, ale nie spamerom
- Zakázať prístup k skrytým súborom a priečinkom
- Zakázanie prístupu k zálohám a zdrojovým súborom
- Zakázanie prehliadania priečinka
- Zakázanie hotlinkovania obrázkov
- Priečinok chránený heslom
- Súbor alebo niekoľko súborov chránených heslom
- Výkon
- Ostatné
Prepisovanie a presmerovanie
Poznámka: Predpokladá sa, že máte nainštalovaný a povolený mod_rewrite.
Presmerovanie na WWW
RewriteEngine on
RewriteCond %{HTTP_HOST} ^example\.com [NC]
RewriteRule ^(.*)$ http://www.example.com/$1 [L,R=301,NC]Všeobecné presmerovanie na WWW
RewriteCond %{HTTP_HOST} !^$
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTPS}s ^on(s)|
RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]Funguje pre akúkoľvek doménu. Source
Presmerovanie bez WWW
Je odporúčané vymazať www z vašej domény. Prekvapenie prekvapenie!
RewriteEngine on
RewriteCond %{HTTP_HOST} ^www\.example\.com [NC]
RewriteRule ^(.*)$ http://example.com/$1 [L,R=301]Presmerovanie na HTTPS
RewriteEngine on
RewriteCond %{HTTPS} !on
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}Pridanie koncového lomítka
RewriteCond %{REQUEST_URI} /+[^\.]+$
RewriteRule ^(.+[^/])$ %{REQUEST_URI}/ [R=301,L]Presmerovanie jednej stránky
Redirect 301 /oldpage.html http://www.yoursite.com/newpage.html
Redirect 301 /oldpage2.html http://www.yoursite.com/folder/Presmerovanie celého webu
Redirect 301 / http://newsite.com/Tento spôsob nezničí linky. Stránka www.oldsite.com/some/crazy/link.html bude presmerovaná na www.newsite.com/some/crazy/link.html. Toto je extrémne nápomocné, ak migrujete web na inú doménu. Zdroj
Bezpečnosť
Zakázanie prístupu pre všetkých
Deny from AllAle pozor, toto zakáže prístup aj vám!
Zakázanie prístupu všetkým okrem vás
Order deny, allow
Deny from All
Allow from xxx.xxx.xxx.xxxxxx.xxx.xxx.xxx je tvoja IP. Ak nahradíš posledné tri čísla napríklad týmto 0/12, bude povolený prístup špecifickému rozashu ip adries vo vašej sieti, toto môže ušetriť čas pri pridávaní IP adries samostatne. Zdroj
Samozrejme je tu aj opačná verzia:
Povoliť prístup všetkým, ale nie spamerom
Order deny, allow
Deny from xxx.xxx.xxx.xxx
Deny from xxx.xxx.xxx.xxyZakázať prístup k skrytým súborom a priečinkom
Skryté súbory a priečinky (tie ktorých názov začína bodkou .) by mali byť väčšinu, ak nie stále chránené. Príklad: .htaccess, .htpasswd, .git, .hg...
RewriteCond %{SCRIPT_FILENAME} -d [OR]
RewriteCond %{SCRIPT_FILENAME} -f
RewriteRule "(^|/)\." - [F]Ako alternatívu môžte použíť Not Found chybu, pri ktorej nemá útočník ani potuchy:
RedirectMatch 404 /\..*$Zakázanie prístupu k zálohám a zdrojovým súborom
Tieto súbory môžu byť pozostatky z text/html editorov (ako Vi/Vim) a predstavujú veľké bezpečnostné riziko, keď k nim má niekto prístup.
<FilesMatch "(\.(bak|config|dist|fla|inc|ini|log|psd|sh|sql|swp)|~)$">
Order allow,deny
Deny from all
Satisfy All
</FilesMatch>Zakázanie prehliadania priečinka
Options All -IndexesZakázanie hotlinkovania obrázkov
RewriteEngine on
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?yourdomain.com [NC]
RewriteRule \.(jpg|jpeg|png|gif)$ - [NC,F,L]Priečinok chránený heslom
Ako prvé potrebujete vytvoriť .htpasswd súbor niekde v systéme:
htpasswd -c /home/fellowship/.htpasswd boromirPotom to môžte použiť na autentifikáciu:
AuthType Basic
AuthName "One does not simply"
AuthUserFile /home/fellowship/.htpasswd
Require valid-userSúbor alebo niekoľko súborov chránených heslom
AuthName "One still does not simply"
AuthType Basic
AuthUserFile /home/fellowship/.htpasswd
<Files "one-ring.o">
Require valid-user
</Files>
<FilesMatch ^((one|two|three)-rings?\.o)$>
Require valid-user
</FilesMatch>Výkon
Kompresia textových súborov
/* Detailed source-code truncated for AI context efficiency. */Nastavenia expirácie headerov
Expires Headers povedia prehliadaču, či by si mal vyžiadať konkrétny súbor zo servera, alebo ho len prevziať z vyrovnávacej pamäte. Je vhodné nastaviť dobu expirácie statického obsahu na dlhú dobu.
Ak nemáte kontrolu verzií na báze mena súboru mali by ste zvážiť dobu uloženia v medzipameti pre súbory ako je CSS a JS na napríklad 1 týždeň. Zdroj
/* Detailed source-code truncated for AI context efficiency. */Vypnutie eTags
Odstránenín ETag headeru zabránite cache a prehliadaču overovať súbory, a tým ich prinútite aby sa spoliehali na svoju Cache-Control a Expires header. Zdroj
<IfModule mod_headers.c>
Header unset ETag
</IfModule>
FileETag NoneOstatné
Nastavenie PHP premenných
php_value <key> <val>
# Príklad:
php_value upload_max_filesize 50M
php_value max_execution_time 240Vlastné chybové stránky
ErrorDocument 400 /errors/breakingbad.html
ErrorDocument 401 /errors/notrespassing.html
ErrorDocument 403 /errors/mordor.html
ErrorDocument 404 /errors/halflife3.html
ErrorDocument 500 /errors/notabugitsafeature.htmlPovinné stiahnutie
Niekedy chcete aby preliadač stiahol obsah namiesto jeho zobrazenia. Toto slúži presne na to.
<Files *.md>
ForceType application/octet-stream
Header set Content-Disposition attachment
</Files>Povoliť cross-domain písma
Fonty pochádzajúce z CDN nemusia pracovať správne vo Firefoxe a IE kvôli CORS. Nasledujúci kód z HTML5Boilerplate by to mal vyriešiť.
<IfModule mod_headers.c>
<FilesMatch "\.(eot|otf|ttc|ttf|woff)$">
Header set Access-Control-Allow-Origin "*"
</FilesMatch>
</IfModule>Automatické UTF-8 kódovanie
Tvoj text by sa mal vždy kódovať v UTF-8, nie?
# Použiť UTF-8 kódovanie pre všetky súbory typu text/plain a text/html
AddDefaultCharset utf-8
# Nastavenie UTF-8 pre niekoľko formátov súborov
AddCharset utf-8 .atom .css .js .json .rss .vtt .xml--- METRICS ---
- Files Extracted: 8
- Estimated Token Budget: ~33019 tokens
- Canonical Reference: https://codewiki.google/github.com/phanan/htaccess