htaccess Documentation

A collection of useful .htaccess snippets.

RAW Doc

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]
.htaccess files 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 .htaccess file 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 the 2.2 branch. 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

Note: It is assumed that you have mod_rewrite installed and enabled.

Force www

apacheconf
RewriteEngine on
RewriteCond %{HTTP_HOST} ^example\.com [NC]
RewriteRule ^(.*)$ https://www.example.com/$1 [L,R=301,NC]

Force www in a Generic Way

apacheconf
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:

apacheconf
RewriteEngine on
RewriteCond %{HTTP_HOST} ^www\.example\.com [NC]
RewriteRule ^(.*)$ https://example.com/$1 [L,R=301]

Force non-www in a Generic Way

apacheconf
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

apacheconf
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.

apacheconf
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}

Force Trailing Slash

apacheconf
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.

apacheconf
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} (.+)/$
RewriteRule ^ %1 [R=301,L]

Source

Redirect a Single Page

apacheconf
Redirect 301 /oldpage.html https://www.example.com/newpage.html
Redirect 301 /oldpage2.html https://www.example.com/folder/

Source

Redirect Using RedirectMatch

apacheconf
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/$1

Source

Alias a Single Directory

apacheconf
RewriteEngine On
RewriteRule ^source-directory/(.*) /target-directory/$1 [R=301,L]

Alias Paths to Script

apacheconf
FallbackResource /index.fcgi

This 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.

apacheconf
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

apacheconf
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.

apacheconf
RewriteEngine On
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule ^([^.]+)$ $1.php [NC,L]

Source

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.

apacheconf
RewriteEngine On
RewriteRule ^robots.txt - [L]

Security

Deny All Access

apacheconf
Require all denied

But wait, this will lock you out from your content as well! Thus introducing...

Deny All Access Except Yours

apacheconf
Require all denied
Require ip xxx.xxx.xxx.xxx

xxx.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'

apacheconf
Require all granted
Require not ip xxx.xxx.xxx.xxx
Require not ip xxx.xxx.xxx.xxy

Deny 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...

apacheconf
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:

apacheconf
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.

apacheconf
<FilesMatch "(\.(bak|config|dist|fla|inc|ini|log|psd|sh|sql|swp)|~)$">
    Require all denied
</FilesMatch>

Source

Disable Directory Browsing

apacheconf
Options All -Indexes

Disable Image Hotlinking

apacheconf
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.

apacheconf
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:

bash
htpasswd -c /home/fellowship/.htpasswd boromir

Then you can use it for authentication:

apacheconf
AuthType Basic
AuthName "One does not simply"
AuthUserFile /home/fellowship/.htpasswd
Require valid-user

Password Protect a File or Several Files

apacheconf
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

apacheconf
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.

apacheconf
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.

apacheconf
SetEnvIf Request_URI "/starry-night" allow_framing=true
Header set X-Frame-Options SAMEORIGIN env=!allow_framing

Content 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.

apacheconf
<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.

apacheconf
<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.

apacheconf
<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.

apacheconf
<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.

apacheconf
ServerSignature Off

Performance

Compress Text Files

text
/* Detailed source-code truncated for AI context efficiency. */

Source

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

text
/* 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.

apacheconf
<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

apacheconf
<IfModule mod_headers.c>
    Header unset ETag
</IfModule>
FileETag None

Miscellaneous

Set PHP Variables

apacheconf
php_value <key> <val>

# For example:
php_value upload_max_filesize 50M
php_value max_execution_time 240

Custom Error Pages

apacheconf
ErrorDocument 500 "Houston, we have a problem."
ErrorDocument 401 https://error.example.com/mordor.html
ErrorDocument 404 /errors/halflife3.html

Custom Maintenance Page

Redirect all traffic to a maintenance page while still allowing access from a specific IP address.

apacheconf
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.

apacheconf
<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.

apacheconf
<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.

apacheconf
<IfModule mod_headers.c>
    <FilesMatch "\.(otf|ttc|ttf|woff|woff2)$">
        Header set Access-Control-Allow-Origin "*"
    </FilesMatch>
</IfModule>

Source

Enable CORS

Enable Cross-Origin Resource Sharing (CORS) for your site, allowing other domains to make requests to your server.

apacheconf
<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?

apacheconf
# 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 .xml

Source

Set Custom MIME Types

Define custom MIME types for file formats that Apache may not recognize by default.

apacheconf
AddType application/manifest+json .webmanifest
AddType application/wasm .wasm
AddType application/x-ndjson .ndjson
AddType text/vtt .vtt

Switch 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.

apacheconf
AddHandler application/x-httpd-php84 .php

# Alternatively, you can use AddType
AddType application/x-httpd-php84 .php

Serve 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.

apacheconf
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

Remarque: On suppose avoir le module mod_rewrite installé et activé.

Forcer www

apacheconf
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

apacheconf
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 :

apacheconf
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

apacheconf
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

apacheconf
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 :

apacheconf
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}

Forcer le slash de fin

apacheconf
RewriteCond %{REQUEST_URI} /+[^\.]+$
RewriteRule ^(.+[^/])$ %{REQUEST_URI}/ [R=301,L]

Supprimer le slash de fin

apacheconf
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$ /$1 [R=301,L]

Rediriger une seule page

apacheconf
Redirect 301 /anciennepage.html http://www.votresite.com/nouvellepage.html
Redirect 301 /anciennepage2.html http://www.votresite.com/dossier/

Source

Alias pour un seul dossier

apacheconf
RewriteEngine On
RewriteRule ^source-directory/(.*) target-directory/$1

Alias de chemins vers un script

apacheconf
FallbackResource /index.fcgi

Cet 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 maintenant
baz.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.

apacheconf
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 directive
FallbackResource), mais offre d'avantage de flexibilité.

Rediriger un site entier

apacheconf
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.

Source

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.

apacheconf
RewriteEngine On
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule ^([^.]+)$ $1.php [NC,L]

Source

Securité

Refuser tout accès

apacheconf
## Apache 2.2
Deny from all

## Apache 2.4
# Require all denied

Mais… 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

apacheconf
## 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.xxx

En 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.

Source

Bien sûr, il y a la version inverse :

Autoriser tout accès sauf aux spammeurs

apacheconf
## 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

Refuser 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...

apacheconf
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 :

apacheconf
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.

apacheconf
<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>

Source

Désactiver la navigation de dossier

apacheconf
Options All -Indexes
apacheconf
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]

Parfois vous souhaitez désactiver le hotlink d'images seulement pour quelques
domaines spécifiques. L'extrait suivant devrait vous aider :

apacheconf
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 :

bash
htpasswd -c /home/fellowship/.htpasswd boromir

Ensuite, vous pouvez utiliser ceci pour activer l'authentification :

apacheconf
AuthType Basic
AuthName "One does not simply"
AuthUserFile /home/fellowship/.htpasswd
Require valid-user

Protéger un ou plusieurs fichiers par mot de passe

apacheconf
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

text
/* Detailed source-code truncated for AI context efficiency. */

Source

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.

text
/* Detailed source-code truncated for AI context efficiency. */

Source

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).

Source

apacheconf
<IfModule mod_headers.c>
    Header unset ETag
</IfModule>
FileETag None

Divers

Définir des variables PHP

apacheconf
php_value <key> <val>

# Par exemple :
php_value upload_max_filesize 50M
php_value max_execution_time 240

Pages d'erreur personnalisées

apacheconf
ErrorDocument 500 "Houston, on a un problème."
ErrorDocument 401 http://error.votredomaine.com/mordor.html
ErrorDocument 404 /errors/halflife3.html

Forcer 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 :

apacheconf
<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 :

apacheconf
<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 :

apacheconf
<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 ?

apacheconf
# 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 .xml

Source

Basculer 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 :

apacheconf
AddHandler application/x-httpd-php55 .php

# Autrement, vous pouvez utiliser AddType
AddType application/x-httpd-php55 .php

Dé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é.

apacheconf
<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.

apacheconf
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]

Source


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

Anmerkung: Es wird vorausgesetzt, dass Sie mod_rewrite installiert und aktiviert haben.

www erzwingen

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

www allgemein erzwingen

apacheconf
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:

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

nicht-www allgemein erzwingen

apacheconf
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

apacheconf
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.

apacheconf
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}

Abschließende Querstriche erzwingen

apacheconf
RewriteCond %{REQUEST_URI} /+[^\.]+$
RewriteRule ^(.+[^/])$ %{REQUEST_URI}/ [R=301,L]

Abschließende Querstriche entfernen

apacheconf
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$ /$1 [R=301,L]

Eine einzelne Seite weiterleiten

apacheconf
Redirect 301 /oldpage.html http://www.example.com/newpage.html
Redirect 301 /oldpage2.html http://www.example.com/folder/

Quelle

Alias für ein einzelnes Verzeichnis hinzufügen

apacheconf
RewriteEngine On
RewriteRule ^source-directory/(.*) target-directory/$1

Verzeichnisalias für ein Skript hinzufügen

apacheconf
FallbackResource /index.fcgi

In 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.

apacheconf
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

apacheconf
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.

apacheconf
RewriteEngine On
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule ^([^.]+)$ $1.php [NC,L]

Quelle

Sicherheit

Kompletten Zugriff verbieten

apacheconf
## Apache 2.2
Deny from all

## Apache 2.4
# Require all denied

Achtung, dadurch werden alle Benutzer, auch Sie selbst, von der Webseite ausgesperrt.

Kompletten Zugriff außer Ihren verbieten

apacheconf
## 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.xxx

xxx.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

apacheconf
## 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

Zugriff 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...

apacheconf
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:

apacheconf
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.

apacheconf
<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>

Quelle

Verzeichnis-Auflistung abschalten

apacheconf
Options All -Indexes

Bild-Hotlinking abschalten

apacheconf
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.

apacheconf
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:

bash
htpasswd -c /home/fellowship/.htpasswd boromir

Dann können Sie diese zur Authentifizierung benutzen:

apacheconf
AuthType Basic
AuthName "One does not simply"
AuthUserFile /home/fellowship/.htpasswd
Require valid-user

Eine oder mehrere Dateien mit Passwort schützen

apacheconf
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

apacheconf
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.

apacheconf
SetEnvIf Request_URI "/starry-night" allow_framing=true
Header set X-Frame-Options SAMEORIGIN env=!allow_framing

Leistung

Textdateien komprimieren

text
/* Detailed source-code truncated for AI context efficiency. */

Quelle

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

text
/* 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

apacheconf
<IfModule mod_headers.c>
    Header unset ETag
</IfModule>
FileETag None

Verschiedenes

PHP-Variablen setzen

apacheconf
php_value <key> <val>

# Zum Beispiel:
php_value upload_max_filesize 50M
php_value max_execution_time 240

Eigene Fehlerseiten

apacheconf
ErrorDocument 500 "Houston, wir haben ein Problem."
ErrorDocument 401 http://error.example.com/mordor.html
ErrorDocument 404 /errors/halflife3.html

Download erzwingen

Manchmal möchten Sie den Browser dazu zwingen, Inhalte herunterzuladen, anstatt sie nur anzuzeigen.

apacheconf
<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.

apacheconf
<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.

apacheconf
<IfModule mod_headers.c>
    <FilesMatch "\.(eot|otf|ttc|ttf|woff|woff2)$">
        Header set Access-Control-Allow-Origin "*"
    </FilesMatch>
</IfModule>

Quelle

Automatische UTF-8-Kodierung

Häufig ist es wünschenswert, dass Text immer als UTF-8 kodiert wird.

apacheconf
# 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 .xml

Quelle

Zu 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.

apacheconf
AddHandler application/x-httpd-php55 .php

# Alternativ können Sie AddType benutzen
AddType application/x-httpd-php55 .php

Kompatibilitä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.

apacheconf
<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.

apacheconf
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]

Quelle


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

Nota: Si presume che mod_rewrite sia installato e abilitato.

Forza www

apacheconf
RewriteEngine on
RewriteCond %{HTTP_HOST} ^esempio\.com [NC]
RewriteRule ^(.*)$ http://www.esempio.com/$1 [L,R=301,NC]

Forza www in maniera generica

apacheconf
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:

apacheconf
RewriteEngine on
RewriteCond %{HTTP_HOST} ^www\.esempio\.com [NC]
RewriteRule ^(.*)$ http://esempio.com/$1 [L,R=301]

Forza non-www in maniera generica

apacheconf
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

apacheconf
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.

apacheconf
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}

Forza Slash Finale

apacheconf
RewriteCond %{REQUEST_URI} /+[^\.]+$
RewriteRule ^(.+[^/])$ %{REQUEST_URI}/ [R=301,L]

Rimuovi Slash Finale

apacheconf
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.

apacheconf
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} (.+)/$
RewriteRule ^ %1 [L,R=301]

Sorgente

Redireziona una singola pagina

apacheconf
Redirect 301 /vecchiapagina.html http://www.esempio.com/nuovapagina.html
Redirect 301 /vecchiapagina2.html http://www.esempio.com/cartella/

Sorgente

Alias di una singola Cartella

apacheconf
RewriteEngine On
RewriteRule ^source-directory/(.*) /target-directory/$1 [R=301,L]

Percorsi Alias a Script

apacheconf
FallbackResource /index.fcgi

Questo 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.

apacheconf
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

apacheconf
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.

apacheconf
RewriteEngine On
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule ^([^.]+)$ $1.php [NC,L]

Sorgente

Sicurezza

Nega tutti gli Accessi

apacheconf
## Apache 2.2
Deny from all

## Apache 2.4
# Require all denied

In questa maniera rimarrai escluso anche tu dai tui contenuti! Per questo introduciamo...

Nega l'accesso a tutti tranne per te stesso

apacheconf
## 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.xxx

xxx.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

apacheconf
## 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

Nega 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...

apacheconf
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:

apacheconf
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.

apacheconf
<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>

Sorgente

Disabilita Esplorazione Cartella

apacheconf
Options All -Indexes

Disabilita Hotlinking delle Immagini

apacheconf
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.

apacheconf
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:

bash
htpasswd -c /home/compagnia/.htpasswd boromir

E adesso potete utilizzarlo per l'autenticazione:

apacheconf
AuthType Basic
AuthName "Non si entra con facilità"
AuthUserFile /home/compagnia/.htpasswd
Require valid-user

Proteggi uno o più file con Password

apacheconf
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

apacheconf
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.

apacheconf
SetEnvIf Request_URI "/starry-night" allow_framing=true
Header set X-Frame-Options SAMEORIGIN env=!allow_framing

Prestazioni

Comprimi i File di Testo

text
/* Detailed source-code truncated for AI context efficiency. */

Sorgente

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

text
/* 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

apacheconf
<IfModule mod_headers.c>
    Header unset ETag
</IfModule>
FileETag None

Miscellanea

Set PHP Variables

apacheconf
php_value <key> <val>

# Peresempio:
php_value upload_max_filesize 50M
php_value max_execution_time 240

Pagine Personalizzate di Errore

apacheconf
ErrorDocument 500 "Houston, abbiamo un problema."
ErrorDocument 401 http://errore.esempio.com/mordor.html
ErrorDocument 404 /errori/halflife3.html

Forza Download

A volte volete poter forzare il browser a scaricare una tipologia di contenuto al posto di mostrarlo.

apacheconf
<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.

apacheconf
<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.

apacheconf
<IfModule mod_headers.c>
    <FilesMatch "\.(eot|otf|ttc|ttf|woff|woff2)$">
        Header set Access-Control-Allow-Origin "*"
    </FilesMatch>
</IfModule>

Sorgente

Codifica automaticamente in UTF-8

Il contenuto del tuo testo de evessere sempre codificato UTF-8 no?

apacheconf
# 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 .xml

Sorgente

Passa 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.

apacheconf
AddHandler application/x-httpd-php55 .php

# Alternatively, you can use AddType
AddType application/x-httpd-php55 .php

Disabilita 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à.

apacheconf
<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.

apacheconf
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]

Sorgente


Overview (`Translations/Japanese/README.md`)

.htaccess Snippets

.htaccessの便利なスニペットのまとめ

免責事項: スニペットを.htaccessで利用した場合、たいていは十分機能するはずですが、一定の修正が必要になることもあります。ご自身の責任で使用してください。

重要: Apache2.4ではいくつかの破壊的変更点があり、それはアクセスコントロールの設定において顕著です。より詳しい情報を知りたい場合は次のリンクをチェックしてください。 upgrading document こちらもどうぞ。 this issue.

クレジット

まとめている、便利なスニペットの大部分はインターネットを通じて収集されたものです。(例えば、かなりの部分は、Apache Server Configsからのものです)。Source等などを正確にクレジットしようと努めていますが、不足してることも考えられます。もしも、ご自分の制作物などがクレジットされるべきだという方がいれば私たちに知らせてください。

目次

URL書き換え&リダイレクト

注: mod_rewriteがインストールされていて有効になってることを前提とします。

wwwありに統一

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

wwwありに統一(包括的に)

apacheconf
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のついたドメインかついてないドメインかは好きなほうにすればよいです。

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

wwwなしに統一(包括的に)

apacheconf
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に統一

apacheconf
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じゃなくなってるいる場合に便利です。

apacheconf
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}

URL末尾をスラッシュ(/)で統一する

apacheconf
RewriteCond %{REQUEST_URI} /+[^\.]+$
RewriteRule ^(.+[^/])$ %{REQUEST_URI}/ [R=301,L]

末尾のスラッシュ(/)を取り除く

apacheconf
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$ /$1 [R=301,L]

決められたページにリダイレクトさせる

apacheconf
Redirect 301 /oldpage.html http://www.example.com/newpage.html
Redirect 301 /oldpage2.html http://www.example.com/folder/

Source

ディレクトリエイリアス設定

apacheconf
RewriteEngine On
RewriteRule ^source-directory/(.*) target-directory/$1

スクリプトへのエイリアスパス

apacheconf
FallbackResource /index.fcgi

存在しないディレクトリまたはファイルへのリクエストがあれば、スクリプト index.fcgi へ転送させるような時に使います。baz.foo/css/style.cssのような実際にファイルがある時はそちらにアクセスさせておいて、baz.foo/some/cool/pathのようなクールなURL表現で、baz.foo/index.fcgi (baz.fooへのリクエストでも同じく扱える)へリクエストを転送させるさせるような時に便利です。あなたのスクリプト環境にさらされるように、PATH_INFO環境変数から元のパスへのアクセスを取得します。

apacheconf
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を扱うより複雑なため)、より柔軟な設定が可能です。

とにかくリダイレクトする

apacheconf
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としてあつかえます。

apacheconf
RewriteEngine On
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule ^([^.]+)$ $1.php [NC,L]

Source

セキュリティ

全アクセス拒否

apacheconf
## Apache 2.2
Deny from all

## Apache 2.4
# Require all denied

あなたも同様にコンテンツをみれなくなるのでよく考えて利用してください。

特定のIPを除いたアクセスの拒否

apacheconf
## 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.xxx

xxx.xxx.xxx.xxxはあなたのIPです。あなたが例えば12桁のIPのうち最後の3桁を0/12で交換する場合、同じネットワーク内のIPの範囲を指定することになり、別途許可IPを全てリストアップしなければいけないような面倒を回避します。
Source

もちろん逆のバージョンもあります。

特定のIPのみアクセスを拒否

apacheconf
## 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 等です。

apacheconf
RewriteCond %{SCRIPT_FILENAME} -d [OR]
RewriteCond %{SCRIPT_FILENAME} -f
RewriteRule "(^|/)\." - [F]

攻撃者に手がかりを与える代わりに、404エラーページを表示させることができます。

apacheconf
RedirectMatch 404 /\..*$

バックアップファイルやソースファイルにアクセスするのを防ぐ

これらのファイルはviやvimによって置かれたり、公にさらされると、セキュリティ上の危険をもたらすファイルである可能性があります。

apacheconf
<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>

Source

ディレクトリ下のファイル一覧の表示禁止

apacheconf
Options All -Indexes

画像直リンクの禁止

apacheconf
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]

特定のドメインからの画像直リンクの禁止

特定のサイトからの画像直リンクを無効にしたい場合です。

apacheconf
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作成してシステムのどこかに配置しておく必要があります。

bash
htpasswd -c /home/fellowship/.htpasswd boromir

そして、作成した.htpasswdを認証のために使うことができます。

apacheconf
AuthType Basic
AuthName "One does not simply"
AuthUserFile /home/fellowship/.htpasswd
Require valid-user

一つか複数かのファイルをパスワードで保護する

apacheconf
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

apacheconf
RewriteEngine on
# Options +FollowSymlinks
RewriteCond %{HTTP_REFERER} somedomain\.com [NC,OR]
RewriteCond %{HTTP_REFERER} anotherdomain\.com
RewriteRule .* - [F]

フレーミングされるのを防ぐ

下記の設定はウェブサイトがフレーム内に表示(IEではiframeを使う)されるのを防止しています。同時に特定のURIの時には許可しています。

apacheconf
SetEnvIf Request_URI "/starry-night" allow_framing=true
Header set X-Frame-Options SAMEORIGIN env=!allow_framing

パフォーマンス

テキストファイルの圧縮

text
/* Detailed source-code truncated for AI context efficiency. */

Source

Expires(有効期限)ヘッダを設定する

ブラウザはexpires (有効期限)ヘッダをみてコンテンツをサーバーから取得すべきか、キャッシュから取得するかを判断します。静的コンテンツの有効期限はいくらか遠い未来に設定したほうがよいといえます。

text
/* Detailed source-code truncated for AI context efficiency. */

Etagをオフにする

ETagヘッダを取り除くことによって、ブラウザ側が持っているキャッシュファイルと、サーバー側にある実ファイルの内容、更新日などが同じかどうか等の検証作業を無効にして、Cache-Control と Expires ヘッダを利用するようにします。

apacheconf
<IfModule mod_headers.c>
    Header unset ETag
</IfModule>
FileETag None

その他の項目

PHPの環境変数をセットする

apacheconf
php_value <key> <val>

# 例:
php_value upload_max_filesize 50M
php_value max_execution_time 240

カスタムのエラーページ

apacheconf
ErrorDocument 500 "Houston, we have a problem."
ErrorDocument 401 http://error.example.com/mordor.html
ErrorDocument 404 /errors/halflife3.html

強制ダウンロード

コンテンツをブラウザに表示させるのではなく、強制的にダウンロードさせたい場合は次のようにします。

apacheconf
<Files *.md>
    ForceType application/octet-stream
    Header set Content-Disposition attachment
</Files>

Now there is a yang to this yin:

ダウンロードを防ぐ

コンテンツをダウンロードさせるのではなく内容をそのままブラウザに表示させたい時は次のようにします。

apacheconf
<FilesMatch "\.(tex|log|aux)$">
    Header set Content-Type text/plain
</FilesMatch>

WEBフォントに対する他のドメインからのアクセスを許可する

IE, Firefoxのだとクロスドメイン制約のため、WEBフォントが正常に機能しない可能性があります。CORS このスニペットはその問題を解決します。

apacheconf
<IfModule mod_headers.c>
    <FilesMatch "\.(eot|otf|ttc|ttf|woff|woff2)$">
        Header set Access-Control-Allow-Origin "*"
    </FilesMatch>
</IfModule>

Source

自動的にUTF8エンコードにする

あなたのテキストコンテンツを常にUTF-8エンコードする時は次の設定をご利用ください。

apacheconf
# text/plain か text/htmlを配信する時はUTF-8を使用します。
AddDefaultCharset utf-8

# 特定のファイルフォーマットで強制的にUTF-8を使う
AddCharset utf-8 .atom .css .js .json .rss .vtt .xml

Source

別のPHPのバージョンに切り替える

もしも、あなたが共有のホストを利用している場合、おそらく複数のバージョンのPHPがインストールされている可能性があり、時には自分のウェブサイトで特定のバージョンのPHPを使いたくなるかもしれません。例えば、ララベルではPHP5.4以上である必要があります。次のスニペットを使えば自分のウェブサイト用のPHPバージョンに切り替える事ができます。

apacheconf
AddHandler application/x-httpd-php55 .php

# 代わりにAddTypeを使うこともできます。
AddType application/x-httpd-php55 .php

インターネットエクスプローラーの互換表示をさせない

IEの互換表示モードはIEにおけるウェブサイトの表示に影響があたえることがあります。次のスニペットを使用することで、IEに最新のエンジンでページをレンダリングさせて、互換表示をさせなくすることができます。

apacheconf
<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)が優先して配信されます。

apacheconf
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]

Source


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

Nota: Presume-se que você tem mod_rewrite instalado e habilitado.

Force www

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

Force www in a Generic Way

apacheconf
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:

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

Force non-www in a Generic Way

apacheconf
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

apacheconf
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.

apacheconf
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}

Force Trailing Slash

apacheconf
RewriteCond %{REQUEST_URI} /+[^\.]+$
RewriteRule ^(.+[^/])$ %{REQUEST_URI}/ [R=301,L]

Remove Trailing Slash

apacheconf
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$ /$1 [R=301,L]

Redirect a Single Page

apacheconf
Redirect 301 /oldpage.html http://www.example.com/newpage.html
Redirect 301 /oldpage2.html http://www.example.com/folder/

Source

Alias a Single Directory

apacheconf
RewriteEngine On
RewriteRule ^source-directory/(.*) target-directory/$1

Alias Paths to Script

apacheconf
FallbackResource /index.fcgi

Este 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.

apacheconf
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

apacheconf
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.

apacheconf
RewriteEngine On
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule ^([^.]+)$ $1.php [NC,L]

Source

Security

Deny All Access

apacheconf
## Apache 2.2
Deny from all

## Apache 2.4
# Require all denied

Mas espere, isso irá bloqueá-lo a partir do seu conteúdo, bem! Assim, a introdução de ...

Deny All Access Except Yours

apacheconf
## 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.xxx

xxx.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'

apacheconf
## 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

Deny 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...

apacheconf
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:

apacheconf
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.

apacheconf
<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>

Source

Disable Directory Browsing

apacheconf
Options All -Indexes

Disable Image Hotlinking

apacheconf
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ó.

apacheconf
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:

bash
htpasswd -c /home/fellowship/.htpasswd boromir

Em seguida, você pode usá-lo para autenticação:

apacheconf
AuthType Basic
AuthName "One does not simply"
AuthUserFile /home/fellowship/.htpasswd
Require valid-user

Password Protect a File or Several Files

apacheconf
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

apacheconf
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.

apacheconf
SetEnvIf Request_URI "/starry-night" allow_framing=true
Header set X-Frame-Options SAMEORIGIN env=!allow_framing

Performance

Compress Text Files

text
/* Detailed source-code truncated for AI context efficiency. */

Source

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

text
/* 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

apacheconf
<IfModule mod_headers.c>
    Header unset ETag
</IfModule>
FileETag None

Miscellaneous

Set PHP Variables

apacheconf
php_value <key> <val>

# Por exemplo:
php_value upload_max_filesize 50M
php_value max_execution_time 240

Custom Error Pages

apacheconf
ErrorDocument 500 "Houston, você tem um problema."
ErrorDocument 401 http://error.example.com/mordor.html
ErrorDocument 404 /errors/halflife3.html

Force Downloading

Às vezes você quer forçar o navegador para baixar algum conteúdo em vez de exibi-lo.

apacheconf
<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.

apacheconf
<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.

apacheconf
<IfModule mod_headers.c>
    <FilesMatch "\.(eot|otf|ttc|ttf|woff|woff2)$">
        Header set Access-Control-Allow-Origin "*"
    </FilesMatch>
</IfModule>

Source

Auto UTF-8 Encode

Seu texto deve ser sempre codificação UTF-8, não?

apacheconf
# 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 .xml

Source

Switch 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ê.

apacheconf
AddHandler application/x-httpd-php55 .php

# Alternativamente, você pode usar AddType
AddType application/x-httpd-php55 .php

Disable 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.

apacheconf
<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.

apacheconf
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]

Source


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

Примечание: Предполагается, что модуль mod_rewrite установлен и включен.

Перенаправление с без www на с www

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

Перенаправление с без www на с www для HTTP или HTTPS

apacheconf
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, но если вы поклонник "чистых" доменов, то:

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

Перенаправление с www на без www для HTTP или HTTPS

apacheconf
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

apacheconf
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.

apacheconf
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}

Вставить завершающий слэш

apacheconf
RewriteCond %{REQUEST_URI} /+[^\.]+$
RewriteRule ^(.+[^/])$ %{REQUEST_URI}/ [R=301,L]

Удалить завершающий слэш

Этот сниппет перенаправляет из пути, который заканчивается на слэш, на путь без завершающего слэша (кроме реальных директорий), например, из http://www.example.com/blog/ перенаправит на http://www.example.com/blog.
Это важно для SEO, так как рекомендуется, чтобы каждая страница имела канонический URL.

apacheconf
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} (.+)/$
RewriteRule ^ %1 [R=301,L]

Источник

Редирект со страницы на страницу

apacheconf
Redirect 301 /oldpage.html http://www.example.com/newpage.html
Redirect 301 /oldpage2.html http://www.example.com/folder/

Источник

Редирект с использованием RedirectMatch

apacheconf
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

Источник

Алиас для определенной директории

apacheconf
RewriteEngine On
RewriteRule ^source-directory/(.*) /target-directory/$1 [R=301,L]

Алиас пути до скрипта

apacheconf
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, которая доступна в скриптах.

apacheconf
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), но также и более гибкое.

Редирект всего сайта

apacheconf
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.

apacheconf
RewriteEngine On
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule ^([^.]+)$ $1.php [NC,L]

Источник

Безопасность

Запретить доступ всем

apacheconf
## Apache 2.2
Deny from all

## Apache 2.4
# Require all denied

Подождите-ка, этот сниппет заблокирует доступ к сайту даже для вас! Сейчас исправим это...

Запретить доступ всем, кроме...

apacheconf
## 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.xxx

xxx.xxx.xxx.xxx - это ваш IP. Если вы замените последние три цифры, например, на 0/12, этим вы определите диапазон IP внутри этой сети и это оградит вас от проблемы перечислять по отдельности все разрешённые IP. Источник

И, естественно, противоположная функция к этой:

Разрешить доступ всем, кроме...

apacheconf
## 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...

apacheconf
RewriteCond %{SCRIPT_FILENAME} -d [OR]
RewriteCond %{SCRIPT_FILENAME} -f
RewriteRule "(^|/)\." - [F]

Как вариант, вы можете показывать ошибку Not Found (не найдено), чтобы не давать атакующему подсказку:

apacheconf
RedirectMatch 404 /\..*$

Запретить доступ к файлам

Эти файлы могут быть оставлены некоторыми редакторами text/html (вроде Vi/Vim) и представляют огромную дыру в безопасности, если станут общедоступными.

apacheconf
<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>

Источник

Запретить листинг директорий

apacheconf
Options All -Indexes

Запретить хотлинкинг изображений

apacheconf
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]

Запретить хотлинкинг изображений для определенных доменов

Иногда вам потребуется запретить хотлинкинг только для некоторых доменов.

apacheconf
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 в определенной директории:

bash
htpasswd -c /home/fellowship/.htpasswd ваш_суперсекретный_пароль

И потом использовать этот файл для аутентификации:

apacheconf
AuthType Basic
AuthName "One does not simply"
AuthUserFile /home/fellowship/.htpasswd
Require valid-user

Защитить паролем один или несколько файлов

apacheconf
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

Блокирует доступ для всех пользователей, которые пришли (были перенаправлены) из определенного домена(-ов).
Источник

apacheconf
RewriteEngine on
# Options +FollowSymlinks
RewriteCond %{HTTP_REFERER} somedomain\.com [NC,OR]
RewriteCond %{HTTP_REFERER} anotherdomain\.com
RewriteRule .* - [F]

Запретить рендеринг сайта во фрейме

Этот сниппет запрещает отображение сайта во фрейме (например, в теге iframe), но разрешает отображение сайта во фрейме для определенных URI.

apacheconf
SetEnvIf Request_URI "/starry-night" allow_framing=true
Header set X-Frame-Options SAMEORIGIN env=!allow_framing

Производительность

Сжатие текстовых файлов

text
/* Detailed source-code truncated for AI context efficiency. */

Источник

Установить Expires Headers

Expires headers говорят браузеру, должен ли он загружать файл из сервера или же из кэша. Для статичного контента рекомендуется установить Expires заголовки на что-нибудь далекое в будущем.

Если вы не контролируете изменение версий с помощью перебора, основанного на файлах, подумайте о том, чтобы уменьшить время кэша для CSS и JS, например, до 1 недели. Источник

text
/* Detailed source-code truncated for AI context efficiency. */

Выключить eTags

Удаляя заголовок ETag, вы выключаете кэш и избавляете возможности проверять браузером файлы, следовательно они будут полагаться на заголовки Cache-Control и Expires. Источник

apacheconf
<IfModule mod_headers.c>
    Header unset ETag
</IfModule>
FileETag None

Разное

Настройка PHP

apacheconf
php_value <key> <val>

# Например:
php_value upload_max_filesize 50M
php_value max_execution_time 240

Пользовательские страницы ошибок

apacheconf
ErrorDocument 500 "Хьюстон, у нас проблемы."
ErrorDocument 401 http://error.example.com/mordor.html
ErrorDocument 404 /errors/halflife3.html

Принудительная загрузка (скачивать файл вместо отображения в браузере)

Иногда нужно загрузить запрашиваемый файл, а не отображать его в браузере.

apacheconf
<Files *.md>
    ForceType application/octet-stream
    Header set Content-Disposition attachment
</Files>

А ниже сниппет, который делает это с точностью до наоборот:

Запретить загрузку (отображать plain в браузере)

Иногда нужно отобразить запрашиваемый файл в браузере, а не загружать его.

apacheconf
<FilesMatch "\.(tex|log|aux)$">
    Header set Content-Type text/plain
</FilesMatch>

Разрешить кроссдоменные шрифты

Шрифты, которые хранятся на CDN серверах, могут не работать в Firefox и IE из-за CORS. Данный сниппет решает эту проблему.

apacheconf
<IfModule mod_headers.c>
    <FilesMatch "\.(eot|otf|ttc|ttf|woff|woff2)$">
        Header set Access-Control-Allow-Origin "*"
    </FilesMatch>
</IfModule>

Источник

Установить по умолчанию кодировку UTF-8

Ваш текстовый контент должен быть всегда закодирован в UTF-8, не так ли?

apacheconf
# Используйте кодировку 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 версию.

apacheconf
AddHandler application/x-httpd-php56 .php

# В качестве альтернативы вы можете использовать AddType
AddType application/x-httpd-php56 .php

Выключить просмотр в режиме совместимости в Internet Explorer

Просмотр в режиме совместимости в IE может оказать влияние на то, как отображаются некоторые сайты. Этот сниппет заставляет IE использовать движок Edge Rendering и выключает просмотр в режиме совместимости.

apacheconf
<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.

apacheconf
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

Poznámka: Predpokladá sa, že máte nainštalovaný a povolený mod_rewrite.

Presmerovanie na WWW

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

Všeobecné presmerovanie na WWW

apacheconf
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!

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

Presmerovanie na HTTPS

apacheconf
RewriteEngine on
RewriteCond %{HTTPS} !on
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}

Pridanie koncového lomítka

apacheconf
RewriteCond %{REQUEST_URI} /+[^\.]+$
RewriteRule ^(.+[^/])$ %{REQUEST_URI}/ [R=301,L]

Presmerovanie jednej stránky

apacheconf
Redirect 301 /oldpage.html http://www.yoursite.com/newpage.html
Redirect 301 /oldpage2.html http://www.yoursite.com/folder/

Zdroj

Presmerovanie celého webu

apacheconf
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

apacheconf
Deny from All

Ale pozor, toto zakáže prístup aj vám!

Zakázanie prístupu všetkým okrem vás

apacheconf
Order deny, allow
Deny from All
Allow from xxx.xxx.xxx.xxx

xxx.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

apacheconf
Order deny, allow
Deny from xxx.xxx.xxx.xxx
Deny from xxx.xxx.xxx.xxy

Zaká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...

apacheconf
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:

apacheconf
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.

apacheconf
<FilesMatch "(\.(bak|config|dist|fla|inc|ini|log|psd|sh|sql|swp)|~)$">
    Order allow,deny
    Deny from all
    Satisfy All
</FilesMatch>

Zdroj

Zakázanie prehliadania priečinka

apacheconf
Options All -Indexes

Zakázanie hotlinkovania obrázkov

apacheconf
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:

bash
htpasswd -c /home/fellowship/.htpasswd boromir

Potom to môžte použiť na autentifikáciu:

apacheconf
AuthType Basic
AuthName "One does not simply"
AuthUserFile /home/fellowship/.htpasswd
Require valid-user

Súbor alebo niekoľko súborov chránených heslom

apacheconf
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

text
/* Detailed source-code truncated for AI context efficiency. */

Zdroj

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

text
/* 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

apacheconf
<IfModule mod_headers.c>
    Header unset ETag
</IfModule>
FileETag None

Ostatné

Nastavenie PHP premenných

apacheconf
php_value <key> <val>

# Príklad:
php_value upload_max_filesize 50M
php_value max_execution_time 240

Vlastné chybové stránky

apacheconf
ErrorDocument 400 /errors/breakingbad.html
ErrorDocument 401 /errors/notrespassing.html
ErrorDocument 403 /errors/mordor.html
ErrorDocument 404 /errors/halflife3.html
ErrorDocument 500 /errors/notabugitsafeature.html

Povinné stiahnutie

Niekedy chcete aby preliadač stiahol obsah namiesto jeho zobrazenia. Toto slúži presne na to.

apacheconf
<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ť.

apacheconf
<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?

apacheconf
# 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

Zdroj


--- METRICS ---