Full Code of phanan/htaccess for AI

master 72179f90f0be cached
12 files
160.9 KB
46.0k tokens
1 requests
Download .txt
Repository: phanan/htaccess
Branch: master
Commit: 72179f90f0be
Files: 12
Total size: 160.9 KB

Directory structure:
gitextract_lpi44njq/

├── .editorconfig
├── .github/
│   └── FUNDING.yml
├── CONTRIBUTING.md
├── LICENSE
├── README.md
└── Translations/
    ├── French/
    │   └── README.md
    ├── German/
    │   └── README.md
    ├── Italian/
    │   └── README.md
    ├── Japanese/
    │   └── README.md
    ├── Portuguese-BR/
    │   └── README.md
    ├── Russian/
    │   └── README.md
    └── Slovak/
        └── README.md

================================================
FILE CONTENTS
================================================

================================================
FILE: .editorconfig
================================================
# editorconfig.org

root = true

[*]
charset = utf-8
end_of_line = lf
indent_size = 4
indent_style = space
insert_final_newline = true
trim_trailing_whitespace = true

[*.md]
trim_trailing_whitespace = false


================================================
FILE: .github/FUNDING.yml
================================================
# These are supported funding model platforms

github: [phanan]
open_collective: koel


================================================
FILE: CONTRIBUTING.md
================================================
# Contributing

1. Fork the repo.
2. Add your section following the [styling guide](#styling). One snippet per PR, please!
3. Commit changes.
4. Push your commit.
5. Create a pull request.
6. Wait with your fingers crossed.

## Styling

- Put your snippets into corresponding sections.
- Put the snippet names into the [Table of Contents](README.md#table-of-contents) and link them using relative URLs.
- Use `###` headers for your snippets.
- Use [Title Case](https://en.wikipedia.org/wiki/Letter_case#Title_case) for headers.
- Add some note/description if applicable. People will thank you for that.
- Be grateful. Indicate a source using this format `[Source](link)` if applicable. 
- For Apache-related examples, wrap your commands in a `apacheconf` code block.
- For command-line examples, wrap your commands in a `bash` code block.


================================================
FILE: LICENSE
================================================
Snippets with specified source belong to their respective owners and have
their own license(s), whenever appropriate. 

Other content belongs to the public domain. Refer to <http://unlicense.org>
for more information.


================================================
FILE: README.md
================================================
# .htaccess Snippets [![Awesome](https://cdn.rawgit.com/sindresorhus/awesome/d7305f38d29fed78fa85652e3a63e154dd8e8829/media/badge.svg)](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](https://httpd.apache.org/docs/current/howto/htaccess.html) 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](https://github.com/phanan/htaccess/tree/2.2). For details on the breaking changes between 2.2 and 2.4, see the [upgrading document](https://httpd.apache.org/docs/2.4/upgrading.html) as well as [this issue](https://github.com/phanan/htaccess/issues/2).

## 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](https://github.com/h5bp/server-configs-apache)) 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](#rewrite-and-redirection)
    - [Force www](#force-www)
    - [Force www in a Generic Way](#force-www-in-a-generic-way)
    - [Force non-www](#force-non-www)
    - [Force non-www in a Generic Way](#force-non-www-in-a-generic-way)
    - [Force HTTPS](#force-https)
    - [Force HTTPS Behind a Proxy](#force-https-behind-a-proxy)
    - [Force Trailing Slash](#force-trailing-slash)
    - [Remove Trailing Slash](#remove-trailing-slash)
    - [Redirect a Single Page](#redirect-a-single-page)
    - [Redirect Using RedirectMatch](#redirect-using-redirectmatch)
    - [Alias a Single Directory](#alias-a-single-directory)
    - [Alias Paths to Script](#alias-paths-to-script)
    - [Redirect an Entire Site](#redirect-an-entire-site)
    - [Alias "Clean" URLs](#alias-clean-urls)
    - [Exclude a URL from Redirection](#exclude-url-from-redirection)
- [Security](#security)
    - [Deny All Access](#deny-all-access)
    - [Deny All Access Except Yours](#deny-all-access-except-yours)
    - [Allow All Access Except Spammers'](#allow-all-access-except-spammers)
    - [Deny Access to Hidden Files and Directories](#deny-access-to-hidden-files-and-directories)
    - [Deny Access to Backup and Source Files](#deny-access-to-backup-and-source-files)
    - [Disable Directory Browsing](#disable-directory-browsing)
    - [Disable Image Hotlinking](#disable-image-hotlinking)
    - [Disable Image Hotlinking for Specific Domains](#disable-image-hotlinking-for-specific-domains)
    - [Password Protect a Directory](#password-protect-a-directory)
    - [Password Protect a File or Several Files](#password-protect-a-file-or-several-files)
    - [Block Visitors by Referrer](#block-visitors-by-referrer)
    - [Block Specific User Agents](#block-specific-user-agents)
    - [Prevent Framing the Site](#prevent-framing-the-site)
    - [Content Security Policy (CSP)](#content-security-policy-csp)
    - [Prevent MIME Type Sniffing](#prevent-mime-type-sniffing)
    - [Set Referrer Policy](#set-referrer-policy)
    - [Set Permissions Policy](#set-permissions-policy)
    - [Remove Server Signature](#remove-server-signature)
- [Performance](#performance)
    - [Compress Text Files](#compress-text-files)
    - [Set Expires Headers](#set-expires-headers)
    - [Set Cache-Control Headers](#set-cache-control-headers)
    - [Turn eTags Off](#turn-etags-off)
- [Miscellaneous](#miscellaneous)
    - [Set PHP Variables](#set-php-variables)
    - [Custom Error Pages](#custom-error-pages)
    - [Custom Maintenance Page](#custom-maintenance-page)
    - [Force Downloading](#force-downloading)
    - [Prevent Downloading](#prevent-downloading)
    - [Allow Cross-Domain Fonts](#allow-cross-domain-fonts)
    - [Enable CORS](#enable-cors)
    - [Auto UTF-8 Encode](#auto-utf-8-encode)
    - [Set Custom MIME Types](#set-custom-mime-types)
    - [Switch to Another PHP Version](#switch-to-another-php-version)
    - [Serve WebP/AVIF Images](#serve-webpavif-images)

## 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](https://stackoverflow.com/questions/4916222/htaccess-how-to-force-www-in-a-generic-way)

### Force non-www
It’s [still](https://www.sitepoint.com/domain-www-or-no-www/) [open](https://devcenter.heroku.com/articles/apex-domains) [for](https://yes-www.org/) [debate](https://no-www.org/) 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](https://overit.com/blog/canonical-urls) to have a canonical URL for every page.
``` apacheconf
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} (.+)/$
RewriteRule ^ %1 [R=301,L]
```
[Source](https://stackoverflow.com/questions/21417263/htaccess-add-remove-trailing-slash-from-url#27264788)

### 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](https://css-tricks.com/snippets/htaccess/301-redirects/)

### 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](https://www.askapache.com/htaccess/301-redirect-with-mod_rewrite-or-redirectmatch.html#301_Redirects_RedirectMatch)

### 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](https://css-tricks.com/snippets/htaccess/301-redirects/)

### 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](https://www.abeautifulsite.net/access-pages-without-the-php-extension-using-htaccess/)

### 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](https://speckyboy.com/2013/01/08/useful-htaccess-snippets-and-hacks/)

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](https://github.com/h5bp/server-configs-apache)

### 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](https://www.htaccess-guide.com/deny-visitors-by-referrer/)
``` 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](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy) 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
``` apacheconf
<IfModule mod_deflate.c>

    # Force compression for mangled headers.
    # https://developer.yahoo.com/blogs/ydn/pushing-beyond-gzipping-25601.html
    <IfModule mod_setenvif.c>
        <IfModule mod_headers.c>
            SetEnvIfNoCase ^(Accept-EncodXng|X-cept-Encoding|X{15}|~{15}|-{15})$ ^((gzip|deflate)\s*,?\s*)+|[X~-]{4,13}$ HAVE_Accept-Encoding
            RequestHeader append Accept-Encoding "gzip,deflate" env=HAVE_Accept-Encoding
        </IfModule>
    </IfModule>

    # Compress all output labeled with one of the following MIME-types
    # (mod_filter is required for Apache 2.4)
    <IfModule mod_filter.c>
        AddOutputFilterByType DEFLATE application/atom+xml \
                                      application/javascript \
                                      application/json \
                                      application/rss+xml \
                                      application/x-font-ttf \
                                      application/x-web-app-manifest+json \
                                      application/xhtml+xml \
                                      application/xml \
                                      font/opentype \
                                      image/svg+xml \
                                      image/x-icon \
                                      text/css \
                                      text/html \
                                      text/plain \
                                      text/xml
    </IfModule>

</IfModule>
```
[Source](https://github.com/h5bp/server-configs-apache)


### 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](https://github.com/h5bp/server-configs-apache)
``` apacheconf
<IfModule mod_expires.c>
    ExpiresActive on
    ExpiresDefault                                      "access plus 1 month"

  # CSS
    ExpiresByType text/css                              "access plus 1 year"

  # Data interchange
    ExpiresByType application/json                      "access plus 0 seconds"
    ExpiresByType application/xml                       "access plus 0 seconds"
    ExpiresByType text/xml                              "access plus 0 seconds"

  # Favicon (cannot be renamed!)
    ExpiresByType image/x-icon                          "access plus 1 week"

  # HTML
    ExpiresByType text/html                             "access plus 0 seconds"

  # JavaScript
    ExpiresByType application/javascript                "access plus 1 year"

  # Manifest files
    ExpiresByType application/x-web-app-manifest+json   "access plus 0 seconds"

  # Media
    ExpiresByType audio/ogg                             "access plus 1 month"
    ExpiresByType image/gif                             "access plus 1 month"
    ExpiresByType image/jpeg                            "access plus 1 month"
    ExpiresByType image/png                             "access plus 1 month"
    ExpiresByType video/mp4                             "access plus 1 month"
    ExpiresByType video/ogg                             "access plus 1 month"
    ExpiresByType video/webm                            "access plus 1 month"

  # Web feeds
    ExpiresByType application/atom+xml                  "access plus 1 hour"
    ExpiresByType application/rss+xml                   "access plus 1 hour"

  # Web fonts
    ExpiresByType application/font-woff2                "access plus 1 month"
    ExpiresByType application/font-woff                 "access plus 1 month"
    ExpiresByType application/x-font-ttf                "access plus 1 month"
    ExpiresByType font/opentype                         "access plus 1 month"
    ExpiresByType image/svg+xml                         "access plus 1 month"
</IfModule>
```

### 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](https://www.askapache.com/htaccess/apache-speed-etags.html)
``` 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](https://en.wikipedia.org/wiki/Cross-origin_resource_sharing). 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](https://github.com/h5bp/server-configs-apache/issues/32)

### 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](https://github.com/h5bp/server-configs-apache)

### 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]
```


================================================
FILE: Translations/French/README.md
================================================
# .htaccess Snippets [![Awesome](https://cdn.rawgit.com/sindresorhus/awesome/d7305f38d29fed78fa85652e3a63e154dd8e8829/media/badge.svg)](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](https://httpd.apache.org/docs/2.4/upgrading.html)
ainsi que [cette issue](https://github.com/phanan/htaccess/issues/2).


## 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](https://github.com/h5bp/server-configs-apache).
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](#réécriture-et-redirection)
    - [Forcer www](#forcer-www)
    - [Forcer www d'une manière générique](#forcer-www-dune-manière-générique)
    - [Forcer non-www](#forcer-non-www)
    - [Forcer non-www d'une manière générique](#forcer-non-www-dune-manière-générique)
    - [Forcer HTTPS](#forcer-https)
    - [Forcer HTTPS derrière un proxy](#forcer-https-derrière-un-proxy)
    - [Forcer le slash de fin](#forcer-le-slash-de-fin)
    - [Supprimer le slash de fin](#supprimer-le-slash-de-fin)
    - [Rediriger une seule page](#rediriger-une-seule-page)
    - [Alias pour un seul dossier](#alias-pour-un-seul-dossier)
    - [Alias de chemins vers un script](#alias-de-chemins-vers-un-script)
    - [Rediriger un site entier](#rediriger-un-site-entier)
    - [Alias en URLs propres](#alias-en-urls-propres)
- [Sécurité](#securité)
    - [Refuser tout accès](#refuser-tout-accès)
    - [Refuser tout accès sauf soi-même](#refuser-tout-accès-sauf-soi-même)
    - [Autoriser tout accès sauf aux spammeurs'](#autoriser-tout-accès-sauf-aux-spammeurs)
    - [Refuser l'accès aux fichiers et répertoires cachés](#refuser-laccès-aux-fichiers-et-dossiers-cachés)
    - [Refuser l'accès aux sources et fichiers de sauvegarde](#refuser-laccès-aux-sources-et-fichiers-de-sauvegarde)
    - [Désactiver la navigation de dossier](#désactiver-la-navigation-de-dossier)
    - [Désactiver le hotlink des images](#désactiver-le-hotlink-des-images)
    - [Désactiver le hotlink des images pour des domaines spécifiques](#désactiver-le-hotlink-des-images-pour-des-domaines-spécifiques)
    - [Protéger un dossier par mot de passe](#protéger-un-dossier-par-mot-de-passe)
    - [Protéger un ou plusieurs fichiers par mot de passe](#protéger-un-ou-plusieurs-fichiers-par-mot-de-passe)
- [Performance](#performance)
    - [Compresser les fichiers texte](#compresser-les-fichiers-texte)
    - [Ajouter l'en-tête "Expires"](#ajouter-len-tête-expires)
    - [Désactiver eTags](#désactiver-etags)
- [Divers](#divers)
    - [Définir des variables PHP](#définir-des-variables-php)
    - [Pages d'erreur personnalisées](#pages-derreur-personnalisées)
    - [Forcer le téléchargement](#forcer-le-téléchargement)
    - [Empêcher le téléchargement](#empêcher-le-téléchargement)
    - [Autoriser les polices Cross-Domain](#autoriser-les-polices-cross-domain)
    - [Encodage UTF-8 automatique](#encodage-utf-8-automatique)
    - [Basculer vers une autre version de PHP](#basculer-vers-une-autre-version-de-php)
    - [Désactiver le mode de compatibilité pour Internet Explorer](#désactiver-le-mode-de-compatibilité-pour-internet-explorer)
    - [Servir des images WebP](#servir-des-images-webp)


## 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](https://stackoverflow.com/questions/4916222/htaccess-how-to-force-www-in-a-generic-way)


### Forcer non-www

C'est [toujours](http://www.sitepoint.com/domain-www-or-no-www/)
[en cours](https://devcenter.heroku.com/articles/apex-domains)
[de](http://yes-www.org/) [débat](http://no-www.org/) 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](http://css-tricks.com/snippets/htaccess/301-redirects/)


### 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](http://css-tricks.com/snippets/htaccess/301-redirects/)


### 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](http://www.abeautifulsite.net/access-pages-without-the-php-extension-using-htaccess/)


## 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](http://speckyboy.com/2013/01/08/useful-htaccess-snippets-and-hacks/)

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](https://github.com/h5bp/server-configs-apache)


### Désactiver la navigation de dossier

``` apacheconf
Options All -Indexes
```


### Désactiver le hotlink des images

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


### Désactiver le hotlink des images pour des domaines spécifiques

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

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

``` apacheconf
<IfModule mod_deflate.c>

    # Force compression for mangled headers.
    # https://developer.yahoo.com/blogs/ydn/pushing-beyond-gzipping-25601.html
    <IfModule mod_setenvif.c>
        <IfModule mod_headers.c>
            SetEnvIfNoCase ^(Accept-EncodXng|X-cept-Encoding|X{15}|~{15}|-{15})$ ^((gzip|deflate)\s*,?\s*)+|[X~-]{4,13}$ HAVE_Accept-Encoding
            RequestHeader append Accept-Encoding "gzip,deflate" env=HAVE_Accept-Encoding
        </IfModule>
    </IfModule>

    # Compresse toutes les sorties ayant un de ces types MIME
    # (pour Apache < 2.3.7, vous n'avez pas besoin d'activer `mod_filter`
    #  et vous pouvez supprimer le `<IfModule mod_filter.c>` et `</IfModule>`
    #  comme `AddOutputFilterByType` sera toujours dans les directives du noyau).
    <IfModule mod_filter.c>
        AddOutputFilterByType DEFLATE application/atom+xml \
                                      application/javascript \
                                      application/json \
                                      application/rss+xml \
                                      application/vnd.ms-fontobject \
                                      application/x-font-ttf \
                                      application/x-web-app-manifest+json \
                                      application/xhtml+xml \
                                      application/xml \
                                      font/opentype \
                                      image/svg+xml \
                                      image/x-icon \
                                      text/css \
                                      text/html \
                                      text/plain \
                                      text/x-component \
                                      text/xml
    </IfModule>

</IfModule>
```

[Source](https://github.com/h5bp/server-configs-apache)


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

``` apacheconf
<IfModule mod_expires.c>
    ExpiresActive on
    ExpiresDefault                                      "access plus 1 month"

  # CSS
    ExpiresByType text/css                              "access plus 1 year"

  # Data interchange
    ExpiresByType application/json                      "access plus 0 seconds"
    ExpiresByType application/xml                       "access plus 0 seconds"
    ExpiresByType text/xml                              "access plus 0 seconds"

  # Favicon (cannot be renamed!)
    ExpiresByType image/x-icon                          "access plus 1 week"

  # HTML components (HTCs)
    ExpiresByType text/x-component                      "access plus 1 month"

  # HTML
    ExpiresByType text/html                             "access plus 0 seconds"

  # JavaScript
    ExpiresByType application/javascript                "access plus 1 year"

  # Manifest files
    ExpiresByType application/x-web-app-manifest+json   "access plus 0 seconds"
    ExpiresByType text/cache-manifest                   "access plus 0 seconds"

  # Media
    ExpiresByType audio/ogg                             "access plus 1 month"
    ExpiresByType image/gif                             "access plus 1 month"
    ExpiresByType image/jpeg                            "access plus 1 month"
    ExpiresByType image/png                             "access plus 1 month"
    ExpiresByType video/mp4                             "access plus 1 month"
    ExpiresByType video/ogg                             "access plus 1 month"
    ExpiresByType video/webm                            "access plus 1 month"

  # Web feeds
    ExpiresByType application/atom+xml                  "access plus 1 hour"
    ExpiresByType application/rss+xml                   "access plus 1 hour"

  # Web fonts
    ExpiresByType application/font-woff2                "access plus 1 month"
    ExpiresByType application/font-woff                 "access plus 1 month"
    ExpiresByType application/vnd.ms-fontobject         "access plus 1 month"
    ExpiresByType application/x-font-ttf                "access plus 1 month"
    ExpiresByType font/opentype                         "access plus 1 month"
    ExpiresByType image/svg+xml                         "access plus 1 month"
</IfModule>
```

[Source](https://github.com/h5bp/server-configs-apache)


### 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](http://www.askapache.com/htaccess/apache-speed-etags.html)

``` 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](https://en.wikipedia.org/wiki/Cross-origin_resource_sharing). Le snippet
suivant de [alrra](https://github.com/h5bp/server-configs-apache/issues/32)
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](https://github.com/h5bp/server-configs-apache)


### 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](https://github.com/laravel/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](https://developers.google.com/speed/webp/?csw=1) 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](https://github.com/vincentorback/WebP-images-with-htaccess)


================================================
FILE: 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](https://httpd.apache.org/docs/2.4/upgrading.html) und [dieses Ticket](https://github.com/phanan/htaccess/issues/2) an.

## Danksagungen
Wir sammeln hier hauptsächlich nützliche Ausschnitte aus dem Internet (beispielsweise aus [Apache Server Configs](https://github.com/h5bp/server-configs-apache)) 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](#umschreibung-und-weiterleitung)
    - [www erzwingen](#www-erzwingen)
    - [www allgemein erzwingen](#www-allgemein-erzwingen)
    - [nicht-www erzwingen](#nicht-www-erzwingen)
    - [nicht-www allgemein erzwingen](#nicht-www-allgemein-erzwingen)
    - [HTTPS erzwingen](#https-erzwingen)
    - [HTTPS hinter einem Proxy erzwingen](#https-hinter-einem-proxy-erzwingen)
    - [Abschließende Querstriche erzwingen](#abschlie%C3%9Fende-querstriche-erzwingen)
    - [Abschließende Querstriche entfernen](#abschlie%C3%9Fende-querstriche-entfernen)
    - [Eine einzelne Seite weiterleiten](#eine-einzelne-seite-weiterleiten)
    - [Alias für ein einzelnes Verzeichnis hinzufügen](#alias-f%C3%BCr-ein-einzelnes-verzeichnis-hinzuf%C3%BCgen)
    - [Verzeichnisalias für ein Skript hinzufügen](#verzeichnisalias-f%C3%BCr-ein-skript-hinzuf%C3%BCgen)
    - [Eine komplette Seite weiterleiten](#eine-komplette-seite-weiterleiten)
    - [Alias für "saubere" URLs hinzufügen](#alias-f%C3%BCr-saubere-urls-hinzuf%C3%BCgen)
- [Sicherheit](#sicherheit)
    - [Kompletten Zugriff verbieten](#kompletten-zugriff-verbieten)
    - [Kompletten Zugriff außer Ihren verbieten](#kompletten-zugriff-au%C3%9Fer-ihren-verbieten)
    - [Zugriff erlauben, außer von Spammern](#zugriff-erlauben-au%C3%9Fer-von-spammern)
    - [Zugriff zu versteckten Dateien und Verzeichnissen verbieten](#zugriff-zu-versteckten-dateien-und-verzeichnissen-verbieten)
    - [Zugriff zu Backup- und Quelldateien verbieten](#zugriff-zu-backup--und-quelldateien-verbieten)
    - [Verzeichnis-Auflistung abschalten](#verzeichnis-auflistung-abschalten)
    - [Bild-Hotlinking abschalten](#bild-hotlinking-abschalten)
    - [Bild-Hotlinking für spezielle Domains abschalten](#bild-hotlinking-f%C3%BCr-spezielle-domains-abschalten)
    - [Ein Verzeichnis mit Passwort schützen](#ein-verzeichnis-mit-passwort-sch%C3%BCtzen)
    - [Eine oder mehrere Dateien mit Passwort schützen](#eine-oder-mehrere-dateien-mit-passwort-sch%C3%BCtzen)
    - [Besucher nach Referrer blockieren](#besucher-nach-referrer-blockieren)
    - [Verbieten, die Seite in Frames zu verwenden](#verbieten-die-seite-in-frames-zu-verwenden)
- [Leistung](#leistung)
    - [Textdateien komprimieren](#textdateien-komprimieren)
    - [Ablaufdatum im Header setzen](#ablaufdatum-im-header-setzen)
    - [eTags abschalten](#etags-abschalten)
- [Verschiedenes](#verschiedenes)
    - [PHP Variablen setzen](#php-variablen-setzen)
    - [Eigene Fehlerseiten](#eigene-fehlerseiten)
    - [Download erzwingen](#download-erzwingen)
    - [Download verhindern](#download-verhindern)
    - [Domainübergreifende Schriftarten erlauben](#domain%C3%BCbergreifende-schriftarten-erlauben)
    - [Automatische UTF-8-Kodierung](#automatische-utf-8-kodierung)
    - [Zu einer anderen PHP-Version wechseln](#zu-einer-anderen-php-version-wechseln)
    - [Kompatibilitätsansicht des Internet Explorer deaktivieren](#kompatibilit%C3%A4tsansicht-des-internet-explorer-deaktivieren)
    - [WebP-Bilder bereitstellen](#webp-bilder-bereitstellen)

## 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](https://stackoverflow.com/questions/4916222/htaccess-how-to-force-www-in-a-generic-way)

### nicht-www erzwingen
Es [wird](http://no-www.org/) [noch](http://www.sitepoint.com/domain-www-or-no-www/) [immer](https://devcenter.heroku.com/articles/apex-domains) [diskutiert](http://yes-www.org/), 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](http://css-tricks.com/snippets/htaccess/301-redirects/)

### 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](http://css-tricks.com/snippets/htaccess/301-redirects/)

### 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](http://www.abeautifulsite.net/access-pages-without-the-php-extension-using-htaccess/)

## 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](http://speckyboy.com/2013/01/08/useful-htaccess-snippets-and-hacks/)

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](https://github.com/h5bp/server-configs-apache)

### 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](http://www.htaccess-guide.com/deny-visitors-by-referrer/)
``` 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
``` apacheconf
<IfModule mod_deflate.c>

    # Kompression für verstümmelte Header erzwingen.
    # https://developer.yahoo.com/blogs/ydn/pushing-beyond-gzipping-25601.html
    <IfModule mod_setenvif.c>
        <IfModule mod_headers.c>
            SetEnvIfNoCase ^(Accept-EncodXng|X-cept-Encoding|X{15}|~{15}|-{15})$ ^((gzip|deflate)\s*,?\s*)+|[X~-]{4,13}$ HAVE_Accept-Encoding
            RequestHeader append Accept-Encoding "gzip,deflate" env=HAVE_Accept-Encoding
        </IfModule>
    </IfModule>

    # Alles mit den folgenden MIME-Typen komprimieren:
    # (für Apache-Versionen unter 2.3.7, müssen Sie `mod_filter` nicht aktivieren
    #  und können die Zeilen `<IfModule mod_filter.c>` und `</IfModule>` entfernen
    #  da `AddOutputFilterByType` noch immer in den Hauptdirektiven ist).
    <IfModule mod_filter.c>
        AddOutputFilterByType DEFLATE application/atom+xml \
                                      application/javascript \
                                      application/json \
                                      application/rss+xml \
                                      application/vnd.ms-fontobject \
                                      application/x-font-ttf \
                                      application/x-web-app-manifest+json \
                                      application/xhtml+xml \
                                      application/xml \
                                      font/opentype \
                                      image/svg+xml \
                                      image/x-icon \
                                      text/css \
                                      text/html \
                                      text/plain \
                                      text/x-component \
                                      text/xml
    </IfModule>

</IfModule>
```
[Quelle](https://github.com/h5bp/server-configs-apache)


### 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](https://github.com/h5bp/server-configs-apache)
``` apacheconf
<IfModule mod_expires.c>
    ExpiresActive on
    ExpiresDefault                                      "access plus 1 month"

  # CSS
    ExpiresByType text/css                              "access plus 1 year"

  # Datenaustausch
    ExpiresByType application/json                      "access plus 0 seconds"
    ExpiresByType application/xml                       "access plus 0 seconds"
    ExpiresByType text/xml                              "access plus 0 seconds"

  # Favicon (kann nicht umbenannt werden!)
    ExpiresByType image/x-icon                          "access plus 1 week"

  # HTML-Komponenten (HTCs)
    ExpiresByType text/x-component                      "access plus 1 month"

  # HTML
    ExpiresByType text/html                             "access plus 0 seconds"

  # JavaScript
    ExpiresByType application/javascript                "access plus 1 year"

  # Manifestdateien
    ExpiresByType application/x-web-app-manifest+json   "access plus 0 seconds"
    ExpiresByType text/cache-manifest                   "access plus 0 seconds"

  # Medien
    ExpiresByType audio/ogg                             "access plus 1 month"
    ExpiresByType image/gif                             "access plus 1 month"
    ExpiresByType image/jpeg                            "access plus 1 month"
    ExpiresByType image/png                             "access plus 1 month"
    ExpiresByType video/mp4                             "access plus 1 month"
    ExpiresByType video/ogg                             "access plus 1 month"
    ExpiresByType video/webm                            "access plus 1 month"

  # Web-Feeds
    ExpiresByType application/atom+xml                  "access plus 1 hour"
    ExpiresByType application/rss+xml                   "access plus 1 hour"

  # Web-Schriftarten
    ExpiresByType application/font-woff2                "access plus 1 month"
    ExpiresByType application/font-woff                 "access plus 1 month"
    ExpiresByType application/vnd.ms-fontobject         "access plus 1 month"
    ExpiresByType application/x-font-ttf                "access plus 1 month"
    ExpiresByType font/opentype                         "access plus 1 month"
    ExpiresByType image/svg+xml                         "access plus 1 month"
</IfModule>
```

### 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](http://www.askapache.com/htaccess/apache-speed-etags.html)
``` 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](https://en.wikipedia.org/wiki/Cross-origin_resource_sharing)). 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](https://github.com/h5bp/server-configs-apache/issues/32)

### 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](https://github.com/h5bp/server-configs-apache)

### 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](https://github.com/laravel/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](https://developers.google.com/speed/webp/?csw=1) 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](https://github.com/vincentorback/WebP-images-with-htaccess)


================================================
FILE: Translations/Italian/README.md
================================================
# .htaccess Snippets [![Awesome](https://cdn.rawgit.com/sindresorhus/awesome/d7305f38d29fed78fa85652e3a63e154dd8e8829/media/badge.svg)](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](https://httpd.apache.org/docs/2.4/upgrading.html) oltre a [questa problematica](https://github.com/phanan/htaccess/issues/2).

## Riconoscimenti
Ciò che stiamo facendo è mettere insieme esempi utili da tutto il web (ad esempio, una buona parte viene da [Apache Server Configs](https://github.com/h5bp/server-configs-apache)) 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](#rewrite-and-redirection)
    - [Forza www](#force-www)
    - [Forza www in maniera generica](#force-www-in-a-generic-way)
    - [Forza non-www](#force-non-www)
    - [Forza non-www in maniera generica](#force-non-www-in-a-generic-way)
    - [Forza HTTPS](#force-https)
    - [Forza HTTPS se dietro Proxy](#force-https-behind-a-proxy)
    - [Forza lo Slash finale](#force-trailing-slash)
    - [Rimuovi lo Slash finale](#remove-trailing-slash)
    - [Rimuovi lo Slash finale da percorsi arbitrari](#remove-trailing-slash-from-arbitrary-paths)
    - [Redireziona una singola pagina](#redirect-a-single-page)
    - [Alias a singole Cartelle](#alias-a-single-directory)
    - [Percorsi Alias a Script](#alias-paths-to-script)
    - [Redireziona un Intero Sito](#redirect-an-entire-site)
    - [Alias per URL "Pulite"](#alias-clean-urls)
- [Sicurezza](#security)
    - [Nega tutti gli accessi](#deny-all-access)
    - [Nega l'accesso a tutti tranne per te stesso](#deny-all-access-except-yours)
    - [Permetti a tutti l'accesso tranne agli Spammer](#allow-all-access-except-spammers)
    - [Nega l'accesso a Cartelle e File Nascosti](#deny-access-to-hidden-files-and-directories)
    - [Nega l'accesso a Backup e File Sorgenti](#deny-access-to-backup-and-source-files)
    - [Disabilita l'Esplorazione delle Cartelle](#disable-directory-browsing)
    - [Disabilita Hotlinking delle Immagini](#disable-image-hotlinking)
    - [Disabilita Hotlinking delle Immagini per Domini Specifici](#disable-image-hotlinking-for-specific-domains)
    - [Proteggi una Cartella con Password](#password-protect-a-directory)
    - [Proteggi uno o più file con Password](#password-protect-a-file-or-several-files)
    - [Blocca i visitatori in base al Referrer](#block-visitors-by-referrer)
    - [Previeni l'inclusione del Sito tramite frame (framing)](#prevent-framing-the-site)
- [Prestazioni](#performance)
    - [Comprimi i File di Testo](#compress-text-files)
    - [Imposta header expires](#set-expires-headers)
    - [Disabilita gli eTags](#turn-etags-off)
- [Miscellanea](#miscellaneous)
    - [Imposta variabili PHP](#set-php-variables)
    - [Pagine di Errore Personalizzate](#custom-error-pages)
    - [Forza il Download](#force-downloading)
    - [Previeni il Download](#prevent-downloading)
    - [Permetti i Web Font da domini differenti](#allow-cross-domain-fonts)
    - [Codifica automaticamente in UTF-8](#auto-utf-8-encode)
    - [Passa a una versione diversa di PHP](#switch-to-another-php-version)
    - [Disabilita Visualizzazione Compatibilità di Internet Explorer](#disable-internet-explorer-compatibility-view)
    - [Rendere disponibili immagini in formato WebP](#serve-webp-images)

## 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](https://stackoverflow.com/questions/4916222/htaccess-how-to-force-www-in-a-generic-way)

### Forza non-www
E' [ancora](http://www.sitepoint.com/domain-www-or-no-www/) [aperta](https://devcenter.heroku.com/articles/apex-domains) [la](http://yes-www.org/) [discussione](http://no-www.org/) 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](http://overit.com/blog/canonical-urls) per avere un URL canonico per ogni pagina.
``` apacheconf
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} (.+)/$
RewriteRule ^ %1 [L,R=301]
```
[Sorgente](https://stackoverflow.com/questions/21417263/htaccess-add-remove-trailing-slash-from-url#27264788)

### 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](http://css-tricks.com/snippets/htaccess/301-redirects/)

### 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](http://css-tricks.com/snippets/htaccess/301-redirects/)

### 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](http://www.abeautifulsite.net/access-pages-without-the-php-extension-using-htaccess/)

## 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](http://speckyboy.com/2013/01/08/useful-htaccess-snippets-and-hacks/)

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](https://github.com/h5bp/server-configs-apache)

### 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](http://www.htaccess-guide.com/deny-visitors-by-referrer/)
``` 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
``` apacheconf
<IfModule mod_deflate.c>

    # Forza la compressione per header manipolati (es. da proxy).
    # https://developer.yahoo.com/blogs/ydn/pushing-beyond-gzipping-25601.html
    <IfModule mod_setenvif.c>
        <IfModule mod_headers.c>
            SetEnvIfNoCase ^(Accept-EncodXng|X-cept-Encoding|X{15}|~{15}|-{15})$ ^((gzip|deflate)\s*,?\s*)+|[X~-]{4,13}$ HAVE_Accept-Encoding
            RequestHeader append Accept-Encoding "gzip,deflate" env=HAVE_Accept-Encoding
        </IfModule>
    </IfModule>

    # Comprimi tutto l'output segnato con uno dei seguentiMIME-type
    # (per le versioni di Apache inferiori a 2.3.7 non è necessario abilitare `mod_filter`
    #  ed è possibile rimuovere `<IfModule mod_filter.c>` e `</IfModule>` lines
    #  in quanto `AddOutputFilterByType` è ancora nelle direttive principali).
    <IfModule mod_filter.c>
        AddOutputFilterByType DEFLATE application/atom+xml \
                                      application/javascript \
                                      application/json \
                                      application/rss+xml \
                                      application/vnd.ms-fontobject \
                                      application/x-font-ttf \
                                      application/x-web-app-manifest+json \
                                      application/xhtml+xml \
                                      application/xml \
                                      font/opentype \
                                      image/svg+xml \
                                      image/x-icon \
                                      text/css \
                                      text/html \
                                      text/plain \
                                      text/x-component \
                                      text/xml
    </IfModule>

</IfModule>
```
[Sorgente](https://github.com/h5bp/server-configs-apache)


### 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](https://github.com/h5bp/server-configs-apache)
``` apacheconf
<IfModule mod_expires.c>
    ExpiresActive on
    ExpiresDefault                                      "access plus 1 month"

  # CSS
    ExpiresByType text/css                              "access plus 1 year"

  # Interscambio Dati
    ExpiresByType application/json                      "access plus 0 seconds"
    ExpiresByType application/xml                       "access plus 0 seconds"
    ExpiresByType text/xml                              "access plus 0 seconds"

  # Favicon (non può essere rinominato!)
    ExpiresByType image/x-icon                          "access plus 1 week"

  # componenti HTML (HTC)
    ExpiresByType text/x-component                      "access plus 1 month"

  # HTML
    ExpiresByType text/html                             "access plus 0 seconds"

  # JavaScript
    ExpiresByType application/javascript                "access plus 1 year"

  # File Manifesto
    ExpiresByType application/x-web-app-manifest+json   "access plus 0 seconds"
    ExpiresByType text/cache-manifest                   "access plus 0 seconds"

  # Media
    ExpiresByType audio/ogg                             "access plus 1 month"
    ExpiresByType image/gif                             "access plus 1 month"
    ExpiresByType image/jpeg                            "access plus 1 month"
    ExpiresByType image/png                             "access plus 1 month"
    ExpiresByType video/mp4                             "access plus 1 month"
    ExpiresByType video/ogg                             "access plus 1 month"
    ExpiresByType video/webm                            "access plus 1 month"

  # Feed Web
    ExpiresByType application/atom+xml                  "access plus 1 hour"
    ExpiresByType application/rss+xml                   "access plus 1 hour"

  # Web font
    ExpiresByType application/font-woff2                "access plus 1 month"
    ExpiresByType application/font-woff                 "access plus 1 month"
    ExpiresByType application/vnd.ms-fontobject         "access plus 1 month"
    ExpiresByType application/x-font-ttf                "access plus 1 month"
    ExpiresByType font/opentype                         "access plus 1 month"
    ExpiresByType image/svg+xml                         "access plus 1 month"
</IfModule>
```

### 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](http://www.askapache.com/htaccess/apache-speed-etags.html)
``` 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](https://en.wikipedia.org/wiki/Cross-origin_resource_sharing). 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](https://github.com/h5bp/server-configs-apache/issues/32)

### 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](https://github.com/h5bp/server-configs-apache)

### 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](https://github.com/laravel/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](https://developers.google.com/speed/webp/?csw=1) 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](https://github.com/vincentorback/WebP-images-with-htaccess)


================================================
FILE: Translations/Japanese/README.md
================================================
# .htaccess Snippets
`.htaccess`の便利なスニペットのまとめ

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

**重要**: Apache2.4ではいくつかの破壊的変更点があり、それはアクセスコントロールの設定において顕著です。より詳しい情報を知りたい場合は次のリンクをチェックしてください。 [upgrading document](https://httpd.apache.org/docs/2.4/upgrading.html) こちらもどうぞ。 [this issue](https://github.com/phanan/htaccess/issues/2).

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

## 目次
- [URL書き換え&リダイレクト](#rewrite-and-redirection)
    - [wwwありに統一](#force-www)
    - [wwwありに統一(包括的に)](#force-www-in-a-generic-way)
    - [wwwなしに統一](#force-non-www)
    - [wwwなしに統一(包括的に)](#force-non-www-in-a-generic-way)
    - [httpsに統一](#force-https)
    - [httpsに統一する(リバースプロキシー経由)](#force-https-behind-a-proxy)
    - [URL末尾をスラッシュ(/)で統一する](#force-trailing-slash)
    - [末尾のスラッシュ(/)を取り除く](#remove-trailing-slash)
    - [決められたページにリダイレクトさせる](#redirect-a-single-page)
    - [ディレクトリエイリアス設定](#alias-a-single-directory)
    - [スクリプトへのエイリアスパス](#alias-paths-to-script)
    - [とにかくリダイレクトする](#redirect-an-entire-site)
    - [クリーンURLエイリアス](#alias-clean-urls)
- [セキュリティ](#security)
    - [全アクセス拒否](#deny-all-access)
    - [特定のIPを除いたアクセスの拒否](#deny-all-access-except-yours)
    - [特定のIPのみアクセスを拒否](#allow-all-access-except-spammers)
    - [隠しファイル、隠しディレクトリへのアクセス拒否](#deny-access-to-hidden-files-and-directories)
    - [バックアップファイルやソースファイルにアクセスするのを防ぐ](#deny-access-to-backup-and-source-files)
    - [ディレクトリ下のファイル一覧の表示禁止](#disable-directory-browsing)
    - [画像直リンクの禁止](#disable-image-hotlinking)
    - [特定のドメインからの画像直リンクの禁止](#disable-image-hotlinking-for-specific-domains)
    - [ディレクトリをパスワードで保護する](#password-protect-a-directory)
    - [一つか複数かのファイルをパスワードで保護する](#password-protect-a-file-or-several-files)
    - [特定の他所のサイトからアクセスをブロック](#block-visitors-by-referrer)
    - [フレーミングされるのを防ぐ](#prevent-framing-the-site)
- [パフォーマンス](#performance)
    - [テキストファイルの圧縮](#compress-text-files)
    - [Expires(有効期限)ヘッダを設定する](#set-expires-headers)
    - [Etagをオフにする](#turn-etags-off)
- [その他の項目](#miscellaneous)
    - [PHPの環境変数をセットする](#set-php-variables)
    - [カスタムのエラーページ](#custom-error-pages)
    - [強制ダウンロード](#force-downloading)
    - [ダウンロードを防ぐ](#prevent-downloading)
    - [WEBフォントに対する他のドメインからのアクセスを許可する](#allow-cross-domain-fonts)
    - [自動的にUTF8エンコードにする](#auto-utf-8-encode)
    - [別のPHPのバージョンに切り替える](#switch-to-another-php-version)
    - [インターネットエクスプローラーの互換表示をさせない](#disable-internet-explorer-compatibility-view)
    - [WebP画像の配信](#serve-webp-images)

## <a name="rewrite-and-redirection">URL書き換え&リダイレクト
注: `mod_rewrite`がインストールされていて有効になってることを前提とします。

### <a name="force-www">wwwありに統一
``` apacheconf
RewriteEngine on
RewriteCond %{HTTP_HOST} ^example\.com [NC]
RewriteRule ^(.*)$ http://www.example.com/$1 [L,R=301,NC]
```

### <a name="force-www-in-a-generic-way">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](https://stackoverflow.com/questions/4916222/htaccess-how-to-force-www-in-a-generic-way)


### <a name="force-non-www">wwwなしに統一
参考 [still](http://www.sitepoint.com/domain-www-or-no-www/) [open](https://devcenter.heroku.com/articles/apex-domains) [for](http://yes-www.org/) [debate](http://no-www.org/) wwwのついたドメインかついてないドメインかは好きなほうにすればよいです。

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

### <a name="force-non-www-in-a-generic-way">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]
```

### <a name="force-https">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>
```

### <a name="force-https-behind-a-proxy">httpsに統一する(リバースプロキシー経由)
リバースプロキシーを経由してhttpsじゃなくなってるいる場合に便利です。


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

### <a name="force-trailing-slash">URL末尾をスラッシュ(/)で統一する
``` apacheconf
RewriteCond %{REQUEST_URI} /+[^\.]+$
RewriteRule ^(.+[^/])$ %{REQUEST_URI}/ [R=301,L]
```

### <a name="remove-trailing-slash">末尾のスラッシュ(/)を取り除く
``` apacheconf
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$ /$1 [R=301,L]
```
### <a name="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](http://css-tricks.com/snippets/htaccess/301-redirects/)

### <a name="alias-a-single-directory">ディレクトリエイリアス設定
``` apacheconf
RewriteEngine On
RewriteRule ^source-directory/(.*) target-directory/$1
```

### <a name="alias-paths-to-script">スクリプトへのエイリアスパス
``` 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`を扱うより複雑なため)、より柔軟な設定が可能です。

### <a name="redirect-an-entire-site">とにかくリダイレクトする
``` apacheconf
Redirect 301 / http://newsite.com/
```
この方法はそっくりそのまま別のサイトにリダイレクトさせます。`www.oldsite.com/some/crazy/link.html`にアクセスした場合、`www.newsite.com/some/crazy/link.html`にリダイレクトさせます。新しいドメインに引っ越したときなど、非常に役に立ちます。 [Source](http://css-tricks.com/snippets/htaccess/301-redirects/)


### <a name="alias-clean-urls">クリーン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](http://www.abeautifulsite.net/access-pages-without-the-php-extension-using-htaccess/)

## <a name="security">セキュリティ
### <a name="deny-all-access">全アクセス拒否
``` apacheconf
## Apache 2.2
Deny from all

## Apache 2.4
# Require all denied
```

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

### <a name="deny-all-access-except-yours">特定の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](http://speckyboy.com/2013/01/08/useful-htaccess-snippets-and-hacks/)

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

### <a name="allow-all-access-except-spammers">特定の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
```

### <a name="deny-access-to-hidden-files-and-directories">隠しファイル、隠しディレクトリへのアクセス拒否
ドット`.`ではじまる隠しファイルや隠しディレクトリはいかなる時も安全である(閲覧されないようにする)必要があります。例えば、`.htaccess`, `.htpasswd`, `.git`, `.hg` 等です。
``` apacheconf
RewriteCond %{SCRIPT_FILENAME} -d [OR]
RewriteCond %{SCRIPT_FILENAME} -f
RewriteRule "(^|/)\." - [F]
```

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

``` apacheconf
RedirectMatch 404 /\..*$
```

### <a name="deny-access-to-backup-and-source-files">バックアップファイルやソースファイルにアクセスするのを防ぐ
これらのファイルは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](https://github.com/h5bp/server-configs-apache)

### <a name="disable-directory-browsing">ディレクトリ下のファイル一覧の表示禁止
``` apacheconf
Options All -Indexes
```

### <a name="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)$ - [NC,F,L]

# もしも、直リンクされた画像の代わりにブロックしたことを示す画像を表示させたいのであれば
# `RewriteRule`を次のようにしてください:
# RewriteRule \.(jpe?g|png|gif|bmp) http://example.com/blocked.png [R,L]
```

### <a name="disable-image-hotlinking-for-specific-domains">特定のドメインからの画像直リンクの禁止
特定のサイトからの画像直リンクを無効にしたい場合です。
``` 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]
```

### <a name="password-protect-a-directory">ディレクトリをパスワードで保護する
最初に`.htpasswd`作成してシステムのどこかに配置しておく必要があります。
``` bash
htpasswd -c /home/fellowship/.htpasswd boromir
```

そして、作成した`.htpasswd`を認証のために使うことができます。
``` apacheconf
AuthType Basic
AuthName "One does not simply"
AuthUserFile /home/fellowship/.htpasswd
Require valid-user
```

### <a name="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>
```

### <a name="block-visitors-by-referrer">特定の他所のサイトからアクセスをブロック
この設定は特定のドメインからのアクセスをブロックします
[Source](http://www.htaccess-guide.com/deny-visitors-by-referrer/)
``` apacheconf
RewriteEngine on
# Options +FollowSymlinks
RewriteCond %{HTTP_REFERER} somedomain\.com [NC,OR]
RewriteCond %{HTTP_REFERER} anotherdomain\.com
RewriteRule .* - [F]
```

### <a name="prevent-framing-the-site">フレーミングされるのを防ぐ
下記の設定はウェブサイトがフレーム内に表示(IEでは`iframe`を使う)されるのを防止しています。同時に特定のURIの時には許可しています。
``` apacheconf
SetEnvIf Request_URI "/starry-night" allow_framing=true
Header set X-Frame-Options SAMEORIGIN env=!allow_framing
```

## <a name="performance">パフォーマンス
### <a name="compress-text-files">テキストファイルの圧縮
``` apacheconf
<IfModule mod_deflate.c>

    # Force compression for mangled headers.
    # https://developer.yahoo.com/blogs/ydn/pushing-beyond-gzipping-25601.html
    <IfModule mod_setenvif.c>
        <IfModule mod_headers.c>
            SetEnvIfNoCase ^(Accept-EncodXng|X-cept-Encoding|X{15}|~{15}|-{15})$ ^((gzip|deflate)\s*,?\s*)+|[X~-]{4,13}$ HAVE_Accept-Encoding
            RequestHeader append Accept-Encoding "gzip,deflate" env=HAVE_Accept-Encoding
        </IfModule>
    </IfModule>

    # Compress all output labeled with one of the following MIME-types
    # (for Apache versions below 2.3.7, you don't need to enable `mod_filter`
    #  and can remove the `<IfModule mod_filter.c>` and `</IfModule>` lines
    #  as `AddOutputFilterByType` is still in the core directives).
    <IfModule mod_filter.c>
        AddOutputFilterByType DEFLATE application/atom+xml \
                                      application/javascript \
                                      application/json \
                                      application/rss+xml \
                                      application/vnd.ms-fontobject \
                                      application/x-font-ttf \
                                      application/x-web-app-manifest+json \
                                      application/xhtml+xml \
                                      application/xml \
                                      font/opentype \
                                      image/svg+xml \
                                      image/x-icon \
                                      text/css \
                                      text/html \
                                      text/plain \
                                      text/x-component \
                                      text/xml
    </IfModule>

</IfModule>
```
[Source](https://github.com/h5bp/server-configs-apache)


### <a name="set-expires-headers">Expires(有効期限)ヘッダを設定する
ブラウザはexpires (有効期限)ヘッダをみてコンテンツをサーバーから取得すべきか、キャッシュから取得するかを判断します。静的コンテンツの有効期限はいくらか遠い未来に設定したほうがよいといえます。
``` apacheconf
<IfModule mod_expires.c>
    ExpiresActive on
    ExpiresDefault                                      "access plus 1 month"

  # CSS
    ExpiresByType text/css                              "access plus 1 year"

  # Data interchange
    ExpiresByType application/json                      "access plus 0 seconds"
    ExpiresByType application/xml                       "access plus 0 seconds"
    ExpiresByType text/xml                              "access plus 0 seconds"

  # Favicon (cannot be renamed!)
    ExpiresByType image/x-icon                          "access plus 1 week"

  # HTML components (HTCs)
    ExpiresByType text/x-component                      "access plus 1 month"

  # HTML
    ExpiresByType text/html                             "access plus 0 seconds"

  # JavaScript
    ExpiresByType application/javascript                "access plus 1 year"

  # Manifest files
    ExpiresByType application/x-web-app-manifest+json   "access plus 0 seconds"
    ExpiresByType text/cache-manifest                   "access plus 0 seconds"

  # Media
    ExpiresByType audio/ogg                             "access plus 1 month"
    ExpiresByType image/gif                             "access plus 1 month"
    ExpiresByType image/jpeg                            "access plus 1 month"
    ExpiresByType image/png                             "access plus 1 month"
    ExpiresByType video/mp4                             "access plus 1 month"
    ExpiresByType video/ogg                             "access plus 1 month"
    ExpiresByType video/webm                            "access plus 1 month"

  # Web feeds
    ExpiresByType application/atom+xml                  "access plus 1 hour"
    ExpiresByType application/rss+xml                   "access plus 1 hour"

  # Web fonts
    ExpiresByType application/font-woff2                "access plus 1 month"
    ExpiresByType application/font-woff                 "access plus 1 month"
    ExpiresByType application/vnd.ms-fontobject         "access plus 1 month"
    ExpiresByType application/x-font-ttf                "access plus 1 month"
    ExpiresByType font/opentype                         "access plus 1 month"
    ExpiresByType image/svg+xml                         "access plus 1 month"
</IfModule>
```

### <a name="turn-etags-off">Etagをオフにする
`ETag`ヘッダを取り除くことによって、ブラウザ側が持っているキャッシュファイルと、サーバー側にある実ファイルの内容、更新日などが同じかどうか等の検証作業を無効にして、`Cache-Control` と `Expires` ヘッダを利用するようにします。
``` apacheconf
<IfModule mod_headers.c>
    Header unset ETag
</IfModule>
FileETag None
```

## <a name="miscellaneous">その他の項目

### <a name="set-php-variables">PHPの環境変数をセットする
``` apacheconf
php_value <key> <val>

# 例:
php_value upload_max_filesize 50M
php_value max_execution_time 240
```

### <a name="custom-error-pages">カスタムのエラーページ
``` apacheconf
ErrorDocument 500 "Houston, we have a problem."
ErrorDocument 401 http://error.example.com/mordor.html
ErrorDocument 404 /errors/halflife3.html
```

### <a name="force-downloading">強制ダウンロード
コンテンツをブラウザに表示させるのではなく、強制的にダウンロードさせたい場合は次のようにします。
``` apacheconf
<Files *.md>
    ForceType application/octet-stream
    Header set Content-Disposition attachment
</Files>
```

Now there is a yang to this yin:

### <a name="prevent-downloading">ダウンロードを防ぐ
コンテンツをダウンロードさせるのではなく内容をそのままブラウザに表示させたい時は次のようにします。
``` apacheconf
<FilesMatch "\.(tex|log|aux)$">
    Header set Content-Type text/plain
</FilesMatch>
```

### <a name="allow-cross-domain-fonts">WEBフォントに対する他のドメインからのアクセスを許可する
IE, Firefoxのだとクロスドメイン制約のため、WEBフォントが正常に機能しない可能性があります。[CORS](https://en.wikipedia.org/wiki/Cross-origin_resource_sharing) このスニペットはその問題を解決します。
``` apacheconf
<IfModule mod_headers.c>
    <FilesMatch "\.(eot|otf|ttc|ttf|woff|woff2)$">
        Header set Access-Control-Allow-Origin "*"
    </FilesMatch>
</IfModule>
```
[Source](https://github.com/h5bp/server-configs-apache/issues/32)

### <a name="auto-utf-8-encode">自動的に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](https://github.com/h5bp/server-configs-apache)

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

``` apacheconf
AddHandler application/x-httpd-php55 .php

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

### <a name="disable-internet-explorer-compatibility-view">インターネットエクスプローラーの互換表示をさせない
IEの互換表示モードはIEにおけるウェブサイトの表示に影響があたえることがあります。次のスニペットを使用することで、IEに最新のエンジンでページをレンダリングさせて、互換表示をさせなくすることができます。

``` apacheconf
<IfModule mod_headers.c>
    BrowserMatch MSIE is-msie
    Header set X-UA-Compatible IE=edge env=is-msie
</IfModule>
```

### <a name="serve-webp-images">WebP画像の配信
もしも、[WebP images](https://developers.google.com/speed/webp/?csw=1) がサポートされていて、同じでディレクトリ下に、同じ名前のファイル名で、.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](https://github.com/vincentorback/WebP-images-with-htaccess)


================================================
FILE: 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](https://httpd.apache.org/docs/2.4/upgrading.html) bem como [this issue](https://github.com/phanan/htaccess/issues/2).

## 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](https://github.com/h5bp/server-configs-apache)) 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](#rewrite-and-redirection)
    - [Force www](#force-www)
    - [Force www in a Generic Way](#force-www-in-a-generic-way)
    - [Force non-www](#force-non-www)
    - [Force non-www in a Generic Way](#force-non-www-in-a-generic-way)
    - [Force HTTPS](#force-https)
    - [Force HTTPS Behind a Proxy](#force-https-behind-a-proxy)
    - [Force Trailing Slash](#force-trailing-slash)
    - [Remove Trailing Slash](#remove-trailing-slash)
    - [Redirect a Single Page](#redirect-a-single-page)
    - [Alias a Single Directory](#alias-a-single-directory)
    - [Alias Paths to Script](#alias-paths-to-script)
    - [Redirect an Entire Site](#redirect-an-entire-site)
    - [Alias "Clean" URLs](#alias-clean-urls)
- [Security](#security)
    - [Deny All Access](#deny-all-access)
    - [Deny All Access Except Yours](#deny-all-access-except-yours)
    - [Allow All Access Except Spammers'](#allow-all-access-except-spammers)
    - [Deny Access to Hidden Files and Directories](#deny-access-to-hidden-files-and-directories)
    - [Deny Access to Backup and Source Files](#deny-access-to-backup-and-source-files)
    - [Disable Directory Browsing](#disable-directory-browsing)
    - [Disable Image Hotlinking](#disable-image-hotlinking)
    - [Disable Image Hotlinking for Specific Domains](#disable-image-hotlinking-for-specific-domains)
    - [Password Protect a Directory](#password-protect-a-directory)
    - [Password Protect a File or Several Files](#password-protect-a-file-or-several-files)
    - [Block Visitors by Referrer](#block-visitors-by-referrer)
    - [Prevent Framing the Site](#prevent-framing-the-site)
- [Performance](#performance)
    - [Compress Text Files](#compress-text-files)
    - [Set Expires Headers](#set-expires-headers)
    - [Turn eTags Off](#turn-etags-off)
- [Miscellaneous](#miscellaneous)
    - [Set PHP Variables](#set-php-variables)
    - [Custom Error Pages](#custom-error-pages)
    - [Force Downloading](#force-downloading)
    - [Prevent Downloading](#prevent-downloading)
    - [Allow Cross-Domain Fonts](#allow-cross-domain-fonts)
    - [Auto UTF-8 Encode](#auto-utf-8-encode)
    - [Switch to Another PHP Version](#switch-to-another-php-version)
    - [Disable Internet Explorer Compatibility View](#disable-internet-explorer-compatibility-view)
    - [Serve WebP Images](#serve-webp-images)

## 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](https://stackoverflow.com/questions/4916222/htaccess-how-to-force-www-in-a-generic-way)

### Force non-www 
It's [still](http://www.sitepoint.com/domain-www-or-no-www/) [open](https://devcenter.heroku.com/articles/apex-domains) [for](http://yes-www.org/) [debate](http://no-www.org/) 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](http://css-tricks.com/snippets/htaccess/301-redirects/)

### 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](http://css-tricks.com/snippets/htaccess/301-redirects/)

### 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](http://www.abeautifulsite.net/access-pages-without-the-php-extension-using-htaccess/)

## 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](http://speckyboy.com/2013/01/08/useful-htaccess-snippets-and-hacks/)

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](https://github.com/h5bp/server-configs-apache)

### 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](http://www.htaccess-guide.com/deny-visitors-by-referrer/)
``` 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
``` apacheconf
<IfModule mod_deflate.c>

    # Force compression for mangled headers.
    # https://developer.yahoo.com/blogs/ydn/pushing-beyond-gzipping-25601.html
    <IfModule mod_setenvif.c>
        <IfModule mod_headers.c>
            SetEnvIfNoCase ^(Accept-EncodXng|X-cept-Encoding|X{15}|~{15}|-{15})$ ^((gzip|deflate)\s*,?\s*)+|[X~-]{4,13}$ HAVE_Accept-Encoding
            RequestHeader append Accept-Encoding "gzip,deflate" env=HAVE_Accept-Encoding
        </IfModule>
    </IfModule>

    # Comprimir toda a saída marcada com um dos seguintes procedimentos MIME-types
    # (para versões do Apache 2.3.7 abaixo, você não precisa habilitar `mod_filter`
    #  pode remover as linhas `<IfModule mod_filter.c>` e `</IfModule>` 
    #  como `AddOutputFilterByType` ainda está em diretivas principais).
    <IfModule mod_filter.c>
        AddOutputFilterByType DEFLATE application/atom+xml \
                                      application/javascript \
                                      application/json \
                                      application/rss+xml \
                                      application/vnd.ms-fontobject \
                                      application/x-font-ttf \
                                      application/x-web-app-manifest+json \
                                      application/xhtml+xml \
                                      application/xml \
                                      font/opentype \
                                      image/svg+xml \
                                      image/x-icon \
                                      text/css \
                                      text/html \
                                      text/plain \
                                      text/x-component \
                                      text/xml
    </IfModule>

</IfModule>
```
[Source](https://github.com/h5bp/server-configs-apache)


### 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](https://github.com/h5bp/server-configs-apache)
``` apacheconf
<IfModule mod_expires.c>
    ExpiresActive on
    ExpiresDefault                                      "access plus 1 month"

  # CSS
    ExpiresByType text/css                              "access plus 1 year"

  # Data interchange
    ExpiresByType application/json                      "access plus 0 seconds"
    ExpiresByType application/xml                       "access plus 0 seconds"
    ExpiresByType text/xml                              "access plus 0 seconds"

  # Favicon (cannot be renamed!)
    ExpiresByType image/x-icon                          "access plus 1 week"

  # HTML components (HTCs)
    ExpiresByType text/x-component                      "access plus 1 month"

  # HTML
    ExpiresByType text/html                             "access plus 0 seconds"

  # JavaScript
    ExpiresByType application/javascript                "access plus 1 year"

  # Manifest files
    ExpiresByType application/x-web-app-manifest+json   "access plus 0 seconds"
    ExpiresByType text/cache-manifest                   "access plus 0 seconds"

  # Media
    ExpiresByType audio/ogg                             "access plus 1 month"
    ExpiresByType image/gif                             "access plus 1 month"
    ExpiresByType image/jpeg                            "access plus 1 month"
    ExpiresByType image/png                             "access plus 1 month"
    ExpiresByType video/mp4                             "access plus 1 month"
    ExpiresByType video/ogg                             "access plus 1 month"
    ExpiresByType video/webm                            "access plus 1 month"

  # Web feeds
    ExpiresByType application/atom+xml                  "access plus 1 hour"
    ExpiresByType application/rss+xml                   "access plus 1 hour"

  # Web fonts
    ExpiresByType application/font-woff2                "access plus 1 month"
    ExpiresByType application/font-woff                 "access plus 1 month"
    ExpiresByType application/vnd.ms-fontobject         "access plus 1 month"
    ExpiresByType application/x-font-ttf                "access plus 1 month"
    ExpiresByType font/opentype                         "access plus 1 month"
    ExpiresByType image/svg+xml                         "access plus 1 month"
</IfModule>
```

### 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](http://www.askapache.com/htaccess/apache-speed-etags.html)
``` 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](https://en.wikipedia.org/wiki/Cross-origin_resource_sharing). 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](https://github.com/h5bp/server-configs-apache/issues/32)

### 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](https://github.com/h5bp/server-configs-apache)

### 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](https://github.com/laravel/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](https://developers.google.com/speed/webp/?csw=1) 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](https://github.com/vincentorback/WebP-images-with-htaccess)


================================================
FILE: Translations/Russian/README.md
================================================
# .htaccess сниппеты [![Awesome](https://cdn.rawgit.com/sindresorhus/awesome/d7305f38d29fed78fa85652e3a63e154dd8e8829/media/badge.svg)](https://github.com/sindresorhus/awesome)
Коллекция .htaccess сниппетов, собранных в одном месте.

**Дисклеймер**: Перед тем, как использовать сниппет в файле `.htaccess`, в большинстве случаев необходимо сделать небольшие коррекции (поменять название папки или файла, изменить URL и т.д.). Используйте сниппеты на свой страх и риск.

**ВАЖНО**: В Apache 2.4 появилось несколько важных изменений, особенно в конфигурации управления доступами. Чтобы узнать больше об этих и других изменениях перейдите по этой [ссылке](https://httpd.apache.org/docs/2.4/upgrading.html), а также просмотрите это [ишью](https://github.com/phanan/htaccess/issues/2).

## Поддержка
Что мы делаем? Здесь собраны самые полезные сниппеты для файла `.htaccess` из всего интернета (например, много разных приемов из [Apache Server Configs](https://github.com/h5bp/server-configs-apache) мы собрали в одном месте). Не исключено, что мы могли что-то упустить. Если вы заметили где-то ошибки или несоответствия, пожалуйста, сообщите нам об этом или сделайте Pull Request.
Подробнее о том, как помочь проекту и делать Pull Request'ы, вы можете прочитать в [этой статье](https://habrahabr.ru/post/275219/) на Хабрахабр.

## Содержание
- [Rewrite и Redirect](#rewrite-и-redirect)
    - [Перенаправление с без www на с www](#Перенаправление-с-без-www-на-с-www)
    - [Перенаправление с без www на с www для HTTP или HTTPS](#Перенаправление-с-без-www-на-с-www-для-http-или-https)
    - [Перенаправление с www на без www](#Перенаправление-с-www-на-без-www)
    - [Перенаправление с www на без www для HTTP или HTTPS](#Перенаправление-с-www-на-без-www-для-http-или-https)
    - [Принудительное использование HTTPS](#Принудительное-использование-https)
    - [Принудительное использование HTTPS за прокси](#Принудительное-использование-https-за-прокси)
    - [Вставить завершающий слэш](#Вставить-завершающий-слэш)
    - [Удалить завершающий слэш](#Удалить-завершающий-слэш)
    - [Редирект со страницы на страницу](#Редирект-со-страницы-на-страницу)
    - [Редирект с использованием RedirectMatch](#Редирект-с-использованием-redirectmatch)
    - [Алиас для определенной директории](#Алиас-для-определенной-директории)
    - [Алиас пути до скрипта](#Алиас-пути-до-скрипта)
    - [Редирект всего сайта](#Редирект-всего-сайта)
    - [Использовать чистые URL](#Использовать-чистые-url)
- [Безопасность](#Безопасность)
    - [Запретить доступ всем](#Запретить-доступ-всем)
    - [Запретить доступ всем, кроме...](#Запретить-доступ-всем-кроме)
    - [Разрешить доступ всем, кроме...](#Разрешить-доступ-всем-кроме)
    - [Запретить доступ к скрытым файлам и директориям](#Запретить-доступ-к-скрытым-файлам-и-директориям)
    - [Запретить доступ к файлам](#Запретить-доступ-к-файлам)
    - [Запретить листинг директорий](#Запретить-листинг-директорий)
    - [Запретить хотлинкинг изображений](#Запретить-хотлинкинг-изображений)
    - [Запретить хотлинкинг изображений для определенных доменов](#Запретить-хотлинкинг-изображений-для-определенных-доменов)
    - [Защитить паролем директорию](#Защитить-паролем-директорию)
    - [Защитить паролем один или несколько файлов](#Защитить-паролем-один-или-несколько-файлов)
    - [Заблокировать посетителя по Referrer](#Заблокировать-посетителя-по-referrer)
    - [Запретить рендеринг сайта во фрейме](#Запретить-рендеринг-сайта-во-фрейме)
- [Производительность](#Производительность)
    - [Сжатие текстовых файлов](#Сжатие-текстовых-файлов)
    - [Установить Expires Headers](#Установить-expires-headers)
    - [Выключить eTags](#Выключить-etags)
- [Разное](#Разное)
    - [Настройка PHP](#Настройка-php)
    - [Пользовательские страницы ошибок](#Пользовательские-страницы-ошибок)
    - [Принудительная загрузка (скачивать файл вместо отображения в браузере)](#Принудительная-загрузка-скачивать-файл-вместо-отображения-в-браузере)
    - [Запретить загрузку (отображать plain в браузере)](#Запретить-загрузку-отображать-plain-в-браузере)
    - [Разрешить кроссдоменные шрифты](#Разрешить-кроссдоменные-шрифты)
    - [Установить по умолчанию кодировку UTF-8](#Установить-по-умолчанию-кодировку-utf-8)
    - [Переключиться на другую версию PHP](#Переключиться-на-другую-версию-php)
    - [Выключить режим совместимости в Internet Explorer](#Выключить-режим-совместимости-в-internet-explorer)
    - [Обработка WebP изображений](#Обработка-webp-изображений)

## 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]
```
Это работает для _любого_ домена. [Источник](https://stackoverflow.com/questions/4916222/htaccess-how-to-force-www-in-a-generic-way)

### Перенаправление с www на без www
Это [вечная](http://www.sitepoint.com/domain-www-or-no-www/) [тема](https://devcenter.heroku.com/articles/apex-domains) [для](http://yes-www.org/) [дискуссий](http://no-www.org/) - использовать или не использовать 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, так как [рекомендуется](http://overit.com/blog/canonical-urls), чтобы каждая страница имела канонический URL.
``` apacheconf
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} (.+)/$
RewriteRule ^ %1 [R=301,L]
```
[Источник](https://stackoverflow.com/questions/21417263/htaccess-add-remove-trailing-slash-from-url#27264788)

### Редирект со страницы на страницу
``` apacheconf
Redirect 301 /oldpage.html http://www.example.com/newpage.html
Redirect 301 /oldpage2.html http://www.example.com/folder/
```
[Источник](http://css-tricks.com/snippets/htaccess/301-redirects/)

### Редирект с использованием 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
```
[Источник](http://www.askapache.com/htaccess/301-redirect-with-mod_rewrite-or-redirectmatch.html#301_Redirects_RedirectMatch)

### Алиас для определенной директории
``` 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`. Это очень полезно, когда вы просто переносите сайт на новый домен. [Источник](http://css-tricks.com/snippets/htaccess/301-redirects/)

### Использовать чистые URL
Этот сниппет позволяет использовать "чистые" URL -- без расширения .php, например, `example.com/users` вместо `example.com/users.php`.
``` apacheconf
RewriteEngine On
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule ^([^.]+)$ $1.php [NC,L]
```
[Источник](http://www.abeautifulsite.net/access-pages-without-the-php-extension-using-htaccess/)

## Безопасность
### Запретить доступ всем
``` 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. [Источник](http://speckyboy.com/2013/01/08/useful-htaccess-snippets-and-hacks/)

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

### Разрешить доступ всем, кроме...
``` 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>
```
[Источник](https://github.com/h5bp/server-configs-apache)

### Запретить листинг директорий
``` 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
Блокирует доступ для всех пользователей, которые пришли (были перенаправлены) из определенного домена(-ов).
[Источник](http://www.htaccess-guide.com/deny-visitors-by-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
```

## Производительность
### Сжатие текстовых файлов
``` apacheconf
<IfModule mod_deflate.c>

    # Принудительное сжатие для исковерканных заголовков.
    # https://developer.yahoo.com/blogs/ydn/pushing-beyond-gzipping-25601.html
    <IfModule mod_setenvif.c>
        <IfModule mod_headers.c>
            SetEnvIfNoCase ^(Accept-EncodXng|X-cept-Encoding|X{15}|~{15}|-{15})$ ^((gzip|deflate)\s*,?\s*)+|[X~-]{4,13}$ HAVE_Accept-Encoding
            RequestHeader append Accept-Encoding "gzip,deflate" env=HAVE_Accept-Encoding
        </IfModule>
    </IfModule>

    # Сжимать исходящие данные с одним из следующих MIME типов
    # (для Apache ниже версии 2.3.7 не нужно включать `mod_filter`
    # и вы можете удалить строки `<IfModule mod_filter.c>` и `</IfModule>`
    # так как `AddOutputFilterByType` все еще есть в ядре Apache).
    <IfModule mod_filter.c>
        AddOutputFilterByType DEFLATE application/atom+xml \
                                      application/javascript \
                                      application/json \
                                      application/rss+xml \
                                      application/vnd.ms-fontobject \
                                      application/x-font-ttf \
                                      application/x-web-app-manifest+json \
                                      application/xhtml+xml \
                                      application/xml \
                                      font/opentype \
                                      image/svg+xml \
                                      image/x-icon \
                                      text/css \
                                      text/html \
                                      text/plain \
                                      text/x-component \
                                      text/xml
    </IfModule>

</IfModule>
```
[Источник](https://github.com/h5bp/server-configs-apache)


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

Если вы не контролируете изменение версий с помощью перебора, основанного на файлах, подумайте о том, чтобы уменьшить время кэша для CSS и JS, например, до 1 недели. [Источник](https://github.com/h5bp/server-configs-apache)
``` apacheconf
<IfModule mod_expires.c>
    ExpiresActive on
    ExpiresDefault                                      "access plus 1 month"

  # CSS
    ExpiresByType text/css                              "access plus 1 year"

  # Данные
    ExpiresByType application/json                      "access plus 0 seconds"
    ExpiresByType application/xml                       "access plus 0 seconds"
    ExpiresByType text/xml                              "access plus 0 seconds"

  # Favicon
    ExpiresByType image/x-icon                          "access plus 1 week"

  # HTML компоненты (HTCs)
    ExpiresByType text/x-component                      "access plus 1 month"

  # HTML
    ExpiresByType text/html                             "access plus 0 seconds"

  # JavaScript
    ExpiresByType application/javascript                "access plus 1 year"

  # Файлы манифеста (Manifest)
    ExpiresByType application/x-web-app-manifest+json   "access plus 0 seconds"
    ExpiresByType text/cache-manifest                   "access plus 0 seconds"

  # Медиа
    ExpiresByType audio/ogg                             "access plus 1 month"
    ExpiresByType image/gif                             "access plus 1 month"
    ExpiresByType image/jpeg                            "access plus 1 month"
    ExpiresByType image/png                             "access plus 1 month"
    ExpiresByType video/mp4                             "access plus 1 month"
    ExpiresByType video/ogg                             "access plus 1 month"
    ExpiresByType video/webm                            "access plus 1 month"

  # Фиды
    ExpiresByType application/atom+xml                  "access plus 1 hour"
    ExpiresByType application/rss+xml                   "access plus 1 hour"

  # Web шрифты
    ExpiresByType application/font-woff2                "access plus 1 month"
    ExpiresByType application/font-woff                 "access plus 1 month"
    ExpiresByType application/vnd.ms-fontobject         "access plus 1 month"
    ExpiresByType application/x-font-ttf                "access plus 1 month"
    ExpiresByType font/opentype                         "access plus 1 month"
    ExpiresByType image/svg+xml                         "access plus 1 month"
</IfModule>
```

### Выключить eTags
Удаляя заголовок `ETag`, вы выключаете кэш и избавляете возможности проверять браузером файлы, следовательно они будут полагаться на заголовки `Cache-Control` и `Expires`. [Источник](http://www.askapache.com/htaccess/apache-speed-etags.html)
``` 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](https://ru.wikipedia.org/wiki/Cross-origin_resource_sharing). Данный сниппет решает эту проблему.
``` apacheconf
<IfModule mod_headers.c>
    <FilesMatch "\.(eot|otf|ttc|ttf|woff|woff2)$">
        Header set Access-Control-Allow-Origin "*"
    </FilesMatch>
</IfModule>
```
[Источник](https://github.com/h5bp/server-configs-apache/issues/32)

### Установить по умолчанию кодировку 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
```
[Источник](https://github.com/h5bp/server-configs-apache)

### Переключиться на другую версию 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 изображения](https://developers.google.com/speed/webp/?csw=1) поддерживаюся и изображения с расширениями .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]
```
[Источник](https://github.com/vincentorback/WebP-images-with-htaccess)


================================================
FILE: 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](https://httpd.apache.org/docs/2.4/upgrading.html) a tiež na [this issue](https://github.com/phanan/htaccess/issues/2).

## Tabuľka obsahu
- [Prepisovanie a presmerovanie](#prepisovanie-a-presmerovanie)
    - [Presmerovanie na WWW](#presmerovanie-na-www)
    - [Všeobecné presmerovanie na WWW](#v-eobecn-presmerovanie-na-www)
    - [Presmerovanie bez WWW](#presmerovanie-bez-www)
    - [Presmerovanie na HTTPS](#presmerovanie-na-https)
    - [Pridanie koncového lomítka](#pridanie-koncov-ho-lom-tka)
    - [Presmerovanie jednej stránky](#presmerovanie-jednej-str-nky)
    - [Presmerovanie celého webu](#presmerovanie-cel-ho-webu)
- [Bezpečnosť](#bezpe-nos)
    - [Zakázanie prístupu pre všetkých](#zak-zanie-pr-stupu-pre-v-etk-ch)
    - [Zakázanie prístupu všetkým okrem vás](#zak-zanie-pr-stupu-v-etk-m-okrem-v-s)
    - [Povoliť prístup všetkým, ale nie spamerom](#povoli-pr-stup-v-etk-m-ale-nie-spamerom)
    - [Zakázať prístup k skrytým súborom a priečinkom](#zak-za-pr-stup-k-skryt-m-s-borom-a-prie-inkom)
    - [Zakázanie prístupu k zálohám a zdrojovým súborom](#zak-zanie-pr-stupu-k-z-loh-m-a-zdrojov-m-s-borom)
    - [Zakázanie prehliadania priečinka](#zak-zanie-prehliadania-prie-inka)
    - [Zakázanie hotlinkovania obrázkov](#zak-zanie-hotlinkovania-obr-zkov)
    - [Priečinok chránený heslom](#prie-inok-chr-nen-heslom)
    - [Súbor alebo niekoľko súborov chránených heslom](#s-bor-alebo-nieko-ko-s-borov-chr-nen-ch-heslom)
- [Výkon](#v-kon)
    - [Kompresia textových súborov](#kompresia-textov-ch-s-borov)
    - [Nastavenia expirácie headerov](#nastavenia-expir-cie-headerov)
    - [Vypnutie eTags](#vypnutie-etags)
- [Ostatné](#ostatn)
    - [Nastavenie PHP premenných](#nastavenie-php-premenn-ch)
    - [Vlastné chybové stránky](#vlastn-chybov-str-nky)
    - [Povinné stiahnutie](#povinn-stiahnutie)
    - [Povoliť cross-domain písma](#povoli-cross-domain-p-sma)
    - [Automatické UTF-8 kódovanie](#automatick-utf-8-k-dovanie)

## 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](https://stackoverflow.com/questions/4916222/htaccess-how-to-force-www-in-a-generic-way)

### Presmerovanie bez WWW
Je [odporúčané](http://no-www.org/) 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](http://css-tricks.com/snippets/htaccess/301-redirects/)

### 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](http://css-tricks.com/snippets/htaccess/301-redirects/)

## 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](http://speckyboy.com/2013/01/08/useful-htaccess-snippets-and-hacks/)

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](http://h5bp.com)

### 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
``` apacheconf
<IfModule mod_deflate.c>

    # "Tvrdá" kompresia pre pozmenené hlavičky
    # https://developer.yahoo.com/blogs/ydn/pushing-beyond-gzipping-25601.html
    <IfModule mod_setenvif.c>
        <IfModule mod_headers.c>
            SetEnvIfNoCase ^(Accept-EncodXng|X-cept-Encoding|X{15}|~{15}|-{15})$ ^((gzip|deflate)\s*,?\s*)+|[X~-]{4,13}$ HAVE_Accept-Encoding
            RequestHeader append Accept-Encoding "gzip,deflate" env=HAVE_Accept-Encoding
        </IfModule>
    </IfModule>

    # Komprimovať všetky výstup s týmito konkrétnymi MIME-typmi
    # (pre Apache verzie pod 2.3.7, nepotrebujete povoľovať `mod_filter`
    #  a môžte vymazať `<IfModule mod_filter.c>` a `</IfModule>` riadky
    #  ale `AddOutputFilterByType` je stále jedna zo základných smerníc).
    <IfModule mod_filter.c>
        AddOutputFilterByType DEFLATE application/atom+xml \
                                      application/javascript \
                                      application/json \
                                      application/rss+xml \
                                      application/vnd.ms-fontobject \
                                      application/x-font-ttf \
                                      application/x-web-app-manifest+json \
                                      application/xhtml+xml \
                                      application/xml \
                                      font/opentype \
                                      image/svg+xml \
                                      image/x-icon \
                                      text/css \
                                      text/html \
                                      text/plain \
                                      text/x-component \
                                      text/xml
    </IfModule>

</IfModule>
```
[Zdroj](https://h5bp.com)


### 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](http://h5bp.com)
``` apacheconf
<IfModule mod_expires.c>
    ExpiresActive on
    ExpiresDefault                                      "access plus 1 month"

  # CSS
    ExpiresByType text/css                              "access plus 1 year"

  # Data interchange
    ExpiresByType application/json                      "access plus 0 seconds"
    ExpiresByType application/xml                       "access plus 0 seconds"
    ExpiresByType text/xml                              "access plus 0 seconds"

  # Favicon (cannot be renamed!)
    ExpiresByType image/x-icon                          "access plus 1 week"

  # HTML components (HTCs)
    ExpiresByType text/x-component                      "access plus 1 month"

  # HTML
    ExpiresByType text/html                             "access plus 0 seconds"

  # JavaScript
    ExpiresByType application/javascript                "access plus 1 year"

  # Manifest files
    ExpiresByType application/x-web-app-manifest+json   "access plus 0 seconds"
    ExpiresByType text/cache-manifest                   "access plus 0 seconds"

  # Media
    ExpiresByType audio/ogg                             "access plus 1 month"
    ExpiresByType image/gif                             "access plus 1 month"
    ExpiresByType image/jpeg                            "access plus 1 month"
    ExpiresByType image/png                             "access plus 1 month"
    ExpiresByType video/mp4                             "access plus 1 month"
    ExpiresByType video/ogg                             "access plus 1 month"
    ExpiresByType video/webm                            "access plus 1 month"

  # Web feeds
    ExpiresByType application/atom+xml                  "access plus 1 hour"
    ExpiresByType application/rss+xml                   "access plus 1 hour"

  # Web fonts
    ExpiresByType application/font-woff                 "access plus 1 month"
    ExpiresByType application/vnd.ms-fontobject         "access plus 1 month"
    ExpiresByType application/x-font-ttf                "access plus 1 month"
    ExpiresByType font/opentype                         "access plus 1 month"
    ExpiresByType image/svg+xml                         "access plus 1 month"
</IfModule>
```

### 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](http://www.askapache.com/htaccess/apache-speed-etags.html)
``` 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](https://en.wikipedia.org/wiki/Cross-origin_resource_sharing). Nasledujúci kód z  [HTML5Boilerplate](http://h5bp.com) 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](http://h5bp.com)
Download .txt
gitextract_lpi44njq/

├── .editorconfig
├── .github/
│   └── FUNDING.yml
├── CONTRIBUTING.md
├── LICENSE
├── README.md
└── Translations/
    ├── French/
    │   └── README.md
    ├── German/
    │   └── README.md
    ├── Italian/
    │   └── README.md
    ├── Japanese/
    │   └── README.md
    ├── Portuguese-BR/
    │   └── README.md
    ├── Russian/
    │   └── README.md
    └── Slovak/
        └── README.md
Condensed preview — 12 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (171K chars).
[
  {
    "path": ".editorconfig",
    "chars": 208,
    "preview": "# editorconfig.org\n\nroot = true\n\n[*]\ncharset = utf-8\nend_of_line = lf\nindent_size = 4\nindent_style = space\ninsert_final_"
  },
  {
    "path": ".github/FUNDING.yml",
    "chars": 86,
    "preview": "# These are supported funding model platforms\n\ngithub: [phanan]\nopen_collective: koel\n"
  },
  {
    "path": "CONTRIBUTING.md",
    "chars": 839,
    "preview": "# Contributing\n\n1. Fork the repo.\n2. Add your section following the [styling guide](#styling). One snippet per PR, pleas"
  },
  {
    "path": "LICENSE",
    "chars": 218,
    "preview": "Snippets with specified source belong to their respective owners and have\ntheir own license(s), whenever appropriate. \n\n"
  },
  {
    "path": "README.md",
    "chars": 25320,
    "preview": "# .htaccess Snippets [![Awesome](https://cdn.rawgit.com/sindresorhus/awesome/d7305f38d29fed78fa85652e3a63e154dd8e8829/me"
  },
  {
    "path": "Translations/French/README.md",
    "chars": 20934,
    "preview": "# .htaccess Snippets [![Awesome](https://cdn.rawgit.com/sindresorhus/awesome/d7305f38d29fed78fa85652e3a63e154dd8e8829/me"
  },
  {
    "path": "Translations/German/README.md",
    "chars": 21778,
    "preview": "# .htaccess-Ausschnitte\nEine Sammlung nützlicher .htaccess-Ausschnitte, alle an einem Ort.\n\n**Haftungsausschluss**: Wäh"
  },
  {
    "path": "Translations/Italian/README.md",
    "chars": 21561,
    "preview": "# .htaccess Snippets [![Awesome](https://cdn.rawgit.com/sindresorhus/awesome/d7305f38d29fed78fa85652e3a63e154dd8e8829/me"
  },
  {
    "path": "Translations/Japanese/README.md",
    "chars": 18124,
    "preview": "# .htaccess Snippets\n`.htaccess`の便利なスニペットのまとめ\n\n**免責事項**: スニペットを`.htaccess`で利用した場合、たいていは十分機能するはずですが、一定の修正が必要になることもあります。ご自"
  },
  {
    "path": "Translations/Portuguese-BR/README.md",
    "chars": 20107,
    "preview": "# .htaccess Snippets\nUma coleção de snippets .htaccess úteis, tudo em um só lugar.\n\n**Disclaimer**: ao deixar cair o tre"
  },
  {
    "path": "Translations/Russian/README.md",
    "chars": 22664,
    "preview": "# .htaccess сниппеты [![Awesome](https://cdn.rawgit.com/sindresorhus/awesome/d7305f38d29fed78fa85652e3a63e154dd8e8829/me"
  },
  {
    "path": "Translations/Slovak/README.md",
    "chars": 12882,
    "preview": "# .htaccess Ukážky kódov\nKolekcia užitočných .htaccess súborov, všetky na jednom mieste. Rozhodol som sa vytvoriť tento "
  }
]

About this extraction

This page contains the full source code of the phanan/htaccess GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 12 files (160.9 KB), approximately 46.0k tokens. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!