├── .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 /.editorconfig: -------------------------------------------------------------------------------- 1 | # editorconfig.org 2 | 3 | root = true 4 | 5 | [*] 6 | charset = utf-8 7 | end_of_line = lf 8 | indent_size = 4 9 | indent_style = space 10 | insert_final_newline = true 11 | trim_trailing_whitespace = true 12 | 13 | [*.md] 14 | trim_trailing_whitespace = false 15 | -------------------------------------------------------------------------------- /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # These are supported funding model platforms 2 | 3 | github: [phanan] 4 | open_collective: koel 5 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | 1. Fork the repo. 4 | 2. Add your section following the [styling guide](#styling). One snippet per PR, please! 5 | 3. Commit changes. 6 | 4. Push your commit. 7 | 5. Create a pull request. 8 | 6. Wait with your fingers crossed. 9 | 10 | ## Styling 11 | 12 | - Put your snippets into corresponding sections. 13 | - Put the snippet names into the [Table of Contents](README.md#table-of-contents) and link them using relative URLs. 14 | - Use `###` headers for your snippets. 15 | - Use [Title Case](https://en.wikipedia.org/wiki/Letter_case#Title_case) for headers. 16 | - Add some note/description if applicable. People will thank you for that. 17 | - Be grateful. Indicate a source using this format `[Source](link)` if applicable. 18 | - For Apache-related examples, wrap your commands in a `apacheconf` code block. 19 | - For command-line examples, wrap your commands in a `bash` code block. 20 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Snippets with specified source belong to their respective owners and have 2 | their own license(s), whenever appropriate. 3 | 4 | Other content belongs to the public domain. Refer to 5 | for more information. 6 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # .htaccess Snippets [![Awesome](https://cdn.rawgit.com/sindresorhus/awesome/d7305f38d29fed78fa85652e3a63e154dd8e8829/media/badge.svg)](https://github.com/sindresorhus/awesome) 2 | A collection of useful .htaccess snippets, all in one place. 3 | 4 | **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. 5 | 6 | **Disclaimer**: 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. 7 | 8 | **IMPORTANT**: Apache 2.4 introduces a few breaking changes, most notably in access control configuration. For more information, check the [upgrading document](https://httpd.apache.org/docs/2.4/upgrading.html) as well as [this issue](https://github.com/phanan/htaccess/issues/2). 9 | 10 | ## Credits 11 | 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. 12 | 13 | ## Table of Contents 14 | - [Rewrite and Redirection](#rewrite-and-redirection) 15 | - [Force www](#force-www) 16 | - [Force www in a Generic Way](#force-www-in-a-generic-way) 17 | - [Force non-www](#force-non-www) 18 | - [Force non-www in a Generic Way](#force-non-www-in-a-generic-way) 19 | - [Force HTTPS](#force-https) 20 | - [Force HTTPS Behind a Proxy](#force-https-behind-a-proxy) 21 | - [Force Trailing Slash](#force-trailing-slash) 22 | - [Remove Trailing Slash](#remove-trailing-slash) 23 | - [Redirect a Single Page](#redirect-a-single-page) 24 | - [Redirect Using RedirectMatch](#redirect-using-redirectmatch) 25 | - [Alias a Single Directory](#alias-a-single-directory) 26 | - [Alias Paths to Script](#alias-paths-to-script) 27 | - [Redirect an Entire Site](#redirect-an-entire-site) 28 | - [Alias "Clean" URLs](#alias-clean-urls) 29 | - [Exclude a URL from Redirection](#exclude-url-from-redirection) 30 | - [Security](#security) 31 | - [Deny All Access](#deny-all-access) 32 | - [Deny All Access Except Yours](#deny-all-access-except-yours) 33 | - [Allow All Access Except Spammers'](#allow-all-access-except-spammers) 34 | - [Deny Access to Hidden Files and Directories](#deny-access-to-hidden-files-and-directories) 35 | - [Deny Access to Backup and Source Files](#deny-access-to-backup-and-source-files) 36 | - [Disable Directory Browsing](#disable-directory-browsing) 37 | - [Disable Image Hotlinking](#disable-image-hotlinking) 38 | - [Disable Image Hotlinking for Specific Domains](#disable-image-hotlinking-for-specific-domains) 39 | - [Password Protect a Directory](#password-protect-a-directory) 40 | - [Password Protect a File or Several Files](#password-protect-a-file-or-several-files) 41 | - [Block Visitors by Referrer](#block-visitors-by-referrer) 42 | - [Prevent Framing the Site](#prevent-framing-the-site) 43 | - [Performance](#performance) 44 | - [Compress Text Files](#compress-text-files) 45 | - [Set Expires Headers](#set-expires-headers) 46 | - [Turn eTags Off](#turn-etags-off) 47 | - [Miscellaneous](#miscellaneous) 48 | - [Set PHP Variables](#set-php-variables) 49 | - [Custom Error Pages](#custom-error-pages) 50 | - [Force Downloading](#force-downloading) 51 | - [Prevent Downloading](#prevent-downloading) 52 | - [Allow Cross-Domain Fonts](#allow-cross-domain-fonts) 53 | - [Auto UTF-8 Encode](#auto-utf-8-encode) 54 | - [Switch to Another PHP Version](#switch-to-another-php-version) 55 | - [Disable Internet Explorer Compatibility View](#disable-internet-explorer-compatibility-view) 56 | - [Serve WebP Images](#serve-webp-images) 57 | 58 | ## Rewrite and Redirection 59 | Note: It is assumed that you have `mod_rewrite` installed and enabled. 60 | 61 | ### Force www 62 | ``` apacheconf 63 | RewriteEngine on 64 | RewriteCond %{HTTP_HOST} ^example\.com [NC] 65 | RewriteRule ^(.*)$ http://www.example.com/$1 [L,R=301,NC] 66 | ``` 67 | 68 | ### Force www in a Generic Way 69 | ``` apacheconf 70 | RewriteCond %{HTTP_HOST} !^$ 71 | RewriteCond %{HTTP_HOST} !^www\. [NC] 72 | RewriteCond %{HTTPS}s ^on(s)| 73 | RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L] 74 | ``` 75 | This works for _any_ domain. [Source](https://stackoverflow.com/questions/4916222/htaccess-how-to-force-www-in-a-generic-way) 76 | 77 | ### Force non-www 78 | 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/) whether www or non-www is the way to go, so if you happen to be a fan of bare domains, here you go: 79 | ``` apacheconf 80 | RewriteEngine on 81 | RewriteCond %{HTTP_HOST} ^www\.example\.com [NC] 82 | RewriteRule ^(.*)$ http://example.com/$1 [L,R=301] 83 | ``` 84 | 85 | ### Force non-www in a Generic Way 86 | ``` apacheconf 87 | RewriteEngine on 88 | RewriteCond %{HTTP_HOST} ^www\. 89 | RewriteCond %{HTTPS}s ^on(s)|off 90 | RewriteCond http%1://%{HTTP_HOST} ^(https?://)(www\.)?(.+)$ 91 | RewriteRule ^ %1%3%{REQUEST_URI} [R=301,L] 92 | ``` 93 | 94 | ### Force HTTPS 95 | ``` apacheconf 96 | RewriteEngine on 97 | RewriteCond %{HTTPS} !on 98 | RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} 99 | 100 | # Note: It’s also recommended to enable HTTP Strict Transport Security (HSTS) 101 | # on your HTTPS website to help prevent man-in-the-middle attacks. 102 | # See https://developer.mozilla.org/en-US/docs/Web/Security/HTTP_strict_transport_security 103 | 104 | # Remove "includeSubDomains" if you don't want to enforce HSTS on all subdomains 105 | Header always set Strict-Transport-Security "max-age=31536000;includeSubDomains" 106 | 107 | ``` 108 | 109 | ### Force HTTPS Behind a Proxy 110 | Useful if you have a proxy in front of your server performing TLS termination. 111 | ``` apacheconf 112 | RewriteCond %{HTTP:X-Forwarded-Proto} !https 113 | RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} 114 | ``` 115 | 116 | ### Force Trailing Slash 117 | ``` apacheconf 118 | RewriteCond %{REQUEST_URI} /+[^\.]+$ 119 | RewriteRule ^(.+[^/])$ %{REQUEST_URI}/ [R=301,L] 120 | ``` 121 | 122 | ### Remove Trailing Slash 123 | This snippet will redirect paths ending in slashes to their non-slash-terminated counterparts (except for actual directories), e.g. `http://www.example.com/blog/` to `http://www.example.com/blog`. This is important for SEO, since it’s [recommended](http://overit.com/blog/canonical-urls) to have a canonical URL for every page. 124 | ``` apacheconf 125 | RewriteCond %{REQUEST_FILENAME} !-d 126 | RewriteCond %{REQUEST_URI} (.+)/$ 127 | RewriteRule ^ %1 [R=301,L] 128 | ``` 129 | [Source](https://stackoverflow.com/questions/21417263/htaccess-add-remove-trailing-slash-from-url#27264788) 130 | 131 | ### Redirect a Single Page 132 | ``` apacheconf 133 | Redirect 301 /oldpage.html http://www.example.com/newpage.html 134 | Redirect 301 /oldpage2.html http://www.example.com/folder/ 135 | ``` 136 | [Source](http://css-tricks.com/snippets/htaccess/301-redirects/) 137 | 138 | ### Redirect Using RedirectMatch 139 | ``` apacheconf 140 | RedirectMatch 301 /subdirectory(.*) http://www.newsite.com/newfolder/$1 141 | RedirectMatch 301 ^/(.*).htm$ /$1.html 142 | RedirectMatch 301 ^/200([0-9])/([^01])(.*)$ /$2$3 143 | RedirectMatch 301 ^/category/(.*)$ /$1 144 | RedirectMatch 301 ^/(.*)/htaccesselite-ultimate-htaccess-article.html(.*) /htaccess/htaccess.html 145 | RedirectMatch 301 ^/(.*).html/1/(.*) /$1.html$2 146 | RedirectMatch 301 ^/manual/(.*)$ http://www.php.net/manual/$1 147 | RedirectMatch 301 ^/dreamweaver/(.*)$ /tools/$1 148 | RedirectMatch 301 ^/z/(.*)$ http://static.askapache.com/$1 149 | ``` 150 | [Source](http://www.askapache.com/htaccess/301-redirect-with-mod_rewrite-or-redirectmatch.html#301_Redirects_RedirectMatch) 151 | 152 | ### Alias a Single Directory 153 | ``` apacheconf 154 | RewriteEngine On 155 | RewriteRule ^source-directory/(.*) /target-directory/$1 [R=301,L] 156 | ``` 157 | 158 | ### Alias Paths to Script 159 | ``` apacheconf 160 | FallbackResource /index.fcgi 161 | ``` 162 | 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. 163 | 164 | ``` apacheconf 165 | RewriteEngine On 166 | RewriteRule ^$ index.fcgi/ [QSA,L] 167 | RewriteCond %{REQUEST_FILENAME} !-f 168 | RewriteCond %{REQUEST_FILENAME} !-d 169 | RewriteRule ^(.*)$ index.fcgi/$1 [QSA,L] 170 | ``` 171 | 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. 172 | 173 | ### Redirect an Entire Site 174 | ``` apacheconf 175 | Redirect 301 / http://newsite.com/ 176 | ``` 177 | 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](http://css-tricks.com/snippets/htaccess/301-redirects/) 178 | 179 | ### Alias “Clean” URLs 180 | This snippet lets you use “clean” URLs -- those without a PHP extension, e.g. `example.com/users` instead of `example.com/users.php`. 181 | ``` apacheconf 182 | RewriteEngine On 183 | RewriteCond %{SCRIPT_FILENAME} !-d 184 | RewriteRule ^([^.]+)$ $1.php [NC,L] 185 | ``` 186 | [Source](http://www.abeautifulsite.net/access-pages-without-the-php-extension-using-htaccess/) 187 | 188 | ### Exclude URL from Redirection 189 | 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. 190 | ``` apacheconf 191 | RewriteEngine On 192 | RewriteRule ^robots.txt - [L] 193 | ``` 194 | 195 | ## Security 196 | ### Deny All Access 197 | ``` apacheconf 198 | ## Apache 2.2 199 | Deny from all 200 | 201 | ## Apache 2.4 202 | # Require all denied 203 | ``` 204 | 205 | But wait, this will lock you out from your content as well! Thus introducing... 206 | 207 | ### Deny All Access Except Yours 208 | ``` apacheconf 209 | ## Apache 2.2 210 | Order deny,allow 211 | Deny from all 212 | Allow from xxx.xxx.xxx.xxx 213 | 214 | ## Apache 2.4 215 | # Require all denied 216 | # Require ip xxx.xxx.xxx.xxx 217 | ``` 218 | `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](http://speckyboy.com/2013/01/08/useful-htaccess-snippets-and-hacks/) 219 | 220 | Now of course there's a reversed version: 221 | 222 | ### Allow All Access Except Spammers' 223 | ``` apacheconf 224 | ## Apache 2.2 225 | Order deny,allow 226 | Deny from xxx.xxx.xxx.xxx 227 | Deny from xxx.xxx.xxx.xxy 228 | 229 | ## Apache 2.4 230 | # Require all granted 231 | # Require not ip xxx.xxx.xxx.xxx 232 | # Require not ip xxx.xxx.xxx.xxy 233 | ``` 234 | 235 | ### Deny Access to Hidden Files and Directories 236 | 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`... 237 | ``` apacheconf 238 | RewriteCond %{SCRIPT_FILENAME} -d [OR] 239 | RewriteCond %{SCRIPT_FILENAME} -f 240 | RewriteRule "(^|/)\." - [F] 241 | ``` 242 | 243 | Alternatively, you can just raise a “Not Found” error, giving the attacker no clue: 244 | ``` apacheconf 245 | RedirectMatch 404 /\..*$ 246 | ``` 247 | 248 | ### Deny Access to Backup and Source Files 249 | These files may be left by some text/HTML editors (like Vi/Vim) and pose a great security danger if exposed to public. 250 | ``` apacheconf 251 | 252 | ## Apache 2.2 253 | Order allow,deny 254 | Deny from all 255 | Satisfy All 256 | 257 | ## Apache 2.4 258 | # Require all denied 259 | 260 | ``` 261 | [Source](https://github.com/h5bp/server-configs-apache) 262 | 263 | ### Disable Directory Browsing 264 | ``` apacheconf 265 | Options All -Indexes 266 | ``` 267 | 268 | ### Disable Image Hotlinking 269 | ``` apacheconf 270 | RewriteEngine on 271 | # Remove the following line if you want to block blank referrer too 272 | RewriteCond %{HTTP_REFERER} !^$ 273 | 274 | RewriteCond %{HTTP_REFERER} !^https?://(.+\.)?example.com [NC] 275 | RewriteRule \.(jpe?g|png|gif|bmp)$ - [NC,F,L] 276 | 277 | # If you want to display a “blocked” banner in place of the hotlinked image, 278 | # replace the above rule with: 279 | # RewriteRule \.(jpe?g|png|gif|bmp) http://example.com/blocked.png [R,L] 280 | ``` 281 | 282 | ### Disable Image Hotlinking for Specific Domains 283 | Sometimes you want to disable image hotlinking from some bad guys only. 284 | ``` apacheconf 285 | RewriteEngine on 286 | RewriteCond %{HTTP_REFERER} ^https?://(.+\.)?badsite\.com [NC,OR] 287 | RewriteCond %{HTTP_REFERER} ^https?://(.+\.)?badsite2\.com [NC,OR] 288 | RewriteRule \.(jpe?g|png|gif|bmp)$ - [NC,F,L] 289 | 290 | # If you want to display a “blocked” banner in place of the hotlinked image, 291 | # replace the above rule with: 292 | # RewriteRule \.(jpe?g|png|gif|bmp) http://example.com/blocked.png [R,L] 293 | ``` 294 | 295 | ### Password Protect a Directory 296 | First you need to create a `.htpasswd` file somewhere in the system: 297 | ``` bash 298 | htpasswd -c /home/fellowship/.htpasswd boromir 299 | ``` 300 | 301 | Then you can use it for authentication: 302 | ``` apacheconf 303 | AuthType Basic 304 | AuthName "One does not simply" 305 | AuthUserFile /home/fellowship/.htpasswd 306 | Require valid-user 307 | ``` 308 | 309 | ### Password Protect a File or Several Files 310 | ``` apacheconf 311 | AuthName "One still does not simply" 312 | AuthType Basic 313 | AuthUserFile /home/fellowship/.htpasswd 314 | 315 | 316 | Require valid-user 317 | 318 | 319 | 320 | Require valid-user 321 | 322 | ``` 323 | 324 | ### Block Visitors by Referrer 325 | This denies access for all users who are coming from (referred by) a specific domain. 326 | [Source](http://www.htaccess-guide.com/deny-visitors-by-referrer/) 327 | ``` apacheconf 328 | RewriteEngine on 329 | # Options +FollowSymlinks 330 | RewriteCond %{HTTP_REFERER} somedomain\.com [NC,OR] 331 | RewriteCond %{HTTP_REFERER} anotherdomain\.com 332 | RewriteRule .* - [F] 333 | ``` 334 | 335 | ### Prevent Framing the Site 336 | This prevents the website to be framed (i.e. put into an `iframe` tag), when still allows framing for a specific URI. 337 | ``` apacheconf 338 | SetEnvIf Request_URI "/starry-night" allow_framing=true 339 | Header set X-Frame-Options SAMEORIGIN env=!allow_framing 340 | ``` 341 | 342 | ## Performance 343 | ### Compress Text Files 344 | ``` apacheconf 345 | 346 | 347 | # Force compression for mangled headers. 348 | # https://developer.yahoo.com/blogs/ydn/pushing-beyond-gzipping-25601.html 349 | 350 | 351 | SetEnvIfNoCase ^(Accept-EncodXng|X-cept-Encoding|X{15}|~{15}|-{15})$ ^((gzip|deflate)\s*,?\s*)+|[X~-]{4,13}$ HAVE_Accept-Encoding 352 | RequestHeader append Accept-Encoding "gzip,deflate" env=HAVE_Accept-Encoding 353 | 354 | 355 | 356 | # Compress all output labeled with one of the following MIME-types 357 | # (for Apache versions below 2.3.7, you don't need to enable `mod_filter` 358 | # and can remove the `` and `` lines 359 | # as `AddOutputFilterByType` is still in the core directives). 360 | 361 | AddOutputFilterByType DEFLATE application/atom+xml \ 362 | application/javascript \ 363 | application/json \ 364 | application/rss+xml \ 365 | application/vnd.ms-fontobject \ 366 | application/x-font-ttf \ 367 | application/x-web-app-manifest+json \ 368 | application/xhtml+xml \ 369 | application/xml \ 370 | font/opentype \ 371 | image/svg+xml \ 372 | image/x-icon \ 373 | text/css \ 374 | text/html \ 375 | text/plain \ 376 | text/x-component \ 377 | text/xml 378 | 379 | 380 | 381 | ``` 382 | [Source](https://github.com/h5bp/server-configs-apache) 383 | 384 | 385 | ### Set Expires Headers 386 | _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. 387 | 388 | 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) 389 | ``` apacheconf 390 | 391 | ExpiresActive on 392 | ExpiresDefault "access plus 1 month" 393 | 394 | # CSS 395 | ExpiresByType text/css "access plus 1 year" 396 | 397 | # Data interchange 398 | ExpiresByType application/json "access plus 0 seconds" 399 | ExpiresByType application/xml "access plus 0 seconds" 400 | ExpiresByType text/xml "access plus 0 seconds" 401 | 402 | # Favicon (cannot be renamed!) 403 | ExpiresByType image/x-icon "access plus 1 week" 404 | 405 | # HTML components (HTCs) 406 | ExpiresByType text/x-component "access plus 1 month" 407 | 408 | # HTML 409 | ExpiresByType text/html "access plus 0 seconds" 410 | 411 | # JavaScript 412 | ExpiresByType application/javascript "access plus 1 year" 413 | 414 | # Manifest files 415 | ExpiresByType application/x-web-app-manifest+json "access plus 0 seconds" 416 | ExpiresByType text/cache-manifest "access plus 0 seconds" 417 | 418 | # Media 419 | ExpiresByType audio/ogg "access plus 1 month" 420 | ExpiresByType image/gif "access plus 1 month" 421 | ExpiresByType image/jpeg "access plus 1 month" 422 | ExpiresByType image/png "access plus 1 month" 423 | ExpiresByType video/mp4 "access plus 1 month" 424 | ExpiresByType video/ogg "access plus 1 month" 425 | ExpiresByType video/webm "access plus 1 month" 426 | 427 | # Web feeds 428 | ExpiresByType application/atom+xml "access plus 1 hour" 429 | ExpiresByType application/rss+xml "access plus 1 hour" 430 | 431 | # Web fonts 432 | ExpiresByType application/font-woff2 "access plus 1 month" 433 | ExpiresByType application/font-woff "access plus 1 month" 434 | ExpiresByType application/vnd.ms-fontobject "access plus 1 month" 435 | ExpiresByType application/x-font-ttf "access plus 1 month" 436 | ExpiresByType font/opentype "access plus 1 month" 437 | ExpiresByType image/svg+xml "access plus 1 month" 438 | 439 | ``` 440 | 441 | ### Turn eTags Off 442 | 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](http://www.askapache.com/htaccess/apache-speed-etags.html) 443 | ``` apacheconf 444 | 445 | Header unset ETag 446 | 447 | FileETag None 448 | ``` 449 | 450 | ## Miscellaneous 451 | 452 | ### Set PHP Variables 453 | ``` apacheconf 454 | php_value 455 | 456 | # For example: 457 | php_value upload_max_filesize 50M 458 | php_value max_execution_time 240 459 | ``` 460 | 461 | ### Custom Error Pages 462 | ``` apacheconf 463 | ErrorDocument 500 "Houston, we have a problem." 464 | ErrorDocument 401 http://error.example.com/mordor.html 465 | ErrorDocument 404 /errors/halflife3.html 466 | ``` 467 | 468 | ### Force Downloading 469 | Sometimes you want to force the browser to download some content instead of displaying it. 470 | ``` apacheconf 471 | 472 | ForceType application/octet-stream 473 | Header set Content-Disposition attachment 474 | 475 | ``` 476 | 477 | Now there is a yang to this yin: 478 | 479 | ### Prevent Downloading 480 | Sometimes you want to force the browser to display some content instead of downloading it. 481 | ``` apacheconf 482 | 483 | Header set Content-Type text/plain 484 | 485 | ``` 486 | 487 | ### Allow Cross-Domain Fonts 488 | CDN-served webfonts might not work in Firefox or IE due to [CORS](https://en.wikipedia.org/wiki/Cross-origin_resource_sharing). This snippet solves the problem. 489 | ``` apacheconf 490 | 491 | 492 | Header set Access-Control-Allow-Origin "*" 493 | 494 | 495 | ``` 496 | [Source](https://github.com/h5bp/server-configs-apache/issues/32) 497 | 498 | ### Auto UTF-8 Encode 499 | Your text content should always be UTF-8 encoded, no? 500 | ``` apacheconf 501 | # Use UTF-8 encoding for anything served text/plain or text/html 502 | AddDefaultCharset utf-8 503 | 504 | # Force UTF-8 for a number of file formats 505 | AddCharset utf-8 .atom .css .js .json .rss .vtt .xml 506 | ``` 507 | [Source](https://github.com/h5bp/server-configs-apache) 508 | 509 | ### Switch to Another PHP Version 510 | 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. 511 | 512 | ``` apacheconf 513 | AddHandler application/x-httpd-php56 .php 514 | 515 | # Alternatively, you can use AddType 516 | AddType application/x-httpd-php56 .php 517 | ``` 518 | 519 | ### Disable Internet Explorer Compatibility View 520 | Compatibility View in IE may affect how some websites are displayed. The following snippet should force IE to use the Edge Rendering Engine and disable the Compatibility View. 521 | 522 | ``` apacheconf 523 | 524 | BrowserMatch MSIE is-msie 525 | Header set X-UA-Compatible IE=edge env=is-msie 526 | 527 | ``` 528 | 529 | ### Serve WebP Images 530 | If [WebP images](https://developers.google.com/speed/webp/?csw=1) are supported and an image with a .webp extension and the same name is found at the same place as the jpg/png image that is going to be served, then the WebP image is served instead. 531 | 532 | ``` apacheconf 533 | RewriteEngine On 534 | RewriteCond %{HTTP_ACCEPT} image/webp 535 | RewriteCond %{DOCUMENT_ROOT}/$1.webp -f 536 | RewriteRule (.+)\.(jpe?g|png)$ $1.webp [T=image/webp,E=accept:1] 537 | ``` 538 | [Source](https://github.com/vincentorback/WebP-images-with-htaccess) 539 | -------------------------------------------------------------------------------- /Translations/French/README.md: -------------------------------------------------------------------------------- 1 | # .htaccess Snippets [![Awesome](https://cdn.rawgit.com/sindresorhus/awesome/d7305f38d29fed78fa85652e3a63e154dd8e8829/media/badge.svg)](https://github.com/sindresorhus/awesome) 2 | 3 | > Une collection utile de fragments de configuration de fichier `.htaccess`, le 4 | > tout regroupé dans un seul endroit. 5 | 6 | **Avertissement** : Bien que l'extrait mis dans un fichier `.htaccess` est la 7 | plupart du temps suffisant, il ya des cas où certaines modifications pourraient 8 | être nécessaires. À utiliser à vos propres risques. 9 | 10 | **IMPORTANT** : Apache 2.4 a introduit quelques changements de rupture, 11 | notamment dans la configuration de contrôle d'accès. Pour plus d'information, 12 | consultez le 13 | [document de mise à niveau](https://httpd.apache.org/docs/2.4/upgrading.html) 14 | ainsi que [cette issue](https://github.com/phanan/htaccess/issues/2). 15 | 16 | 17 | ## Crédits 18 | 19 | Ce que nous faisons ici est principalement la collection d'extraits pratiques en 20 | provenance d'un peu partout sur le web, par exemple, une bonne partie provient 21 | du dépôt [Apache Server Configs](https://github.com/h5bp/server-configs-apache). 22 | Bien qu'ayant essayé de créditer la bonne personne, des éléments peuvent être 23 | manquants. Si vous pensez que quelque chose ici provient de votre travail et que 24 | vous devriez en être crédité, faites le moi savoir, ou faites une PR. 25 | 26 | 27 | ## Table des matières 28 | 29 | - [Réécriture et redirection](#réécriture-et-redirection) 30 | - [Forcer www](#forcer-www) 31 | - [Forcer www d'une manière générique](#forcer-www-dune-manière-générique) 32 | - [Forcer non-www](#forcer-non-www) 33 | - [Forcer non-www d'une manière générique](#forcer-non-www-dune-manière-générique) 34 | - [Forcer HTTPS](#forcer-https) 35 | - [Forcer HTTPS derrière un proxy](#forcer-https-derrière-un-proxy) 36 | - [Forcer le slash de fin](#forcer-le-slash-de-fin) 37 | - [Supprimer le slash de fin](#supprimer-le-slash-de-fin) 38 | - [Rediriger une seule page](#rediriger-une-seule-page) 39 | - [Alias pour un seul dossier](#alias-pour-un-seul-dossier) 40 | - [Alias de chemins vers un script](#alias-de-chemins-vers-un-script) 41 | - [Rediriger un site entier](#rediriger-un-site-entier) 42 | - [Alias en URLs propres](#alias-en-urls-propres) 43 | - [Sécurité](#securité) 44 | - [Refuser tout accès](#refuser-tout-accès) 45 | - [Refuser tout accès sauf soi-même](#refuser-tout-accès-sauf-soi-même) 46 | - [Autoriser tout accès sauf aux spammeurs'](#autoriser-tout-accès-sauf-aux-spammeurs) 47 | - [Refuser l'accès aux fichiers et répertoires cachés](#refuser-laccès-aux-fichiers-et-dossiers-cachés) 48 | - [Refuser l'accès aux sources et fichiers de sauvegarde](#refuser-laccès-aux-sources-et-fichiers-de-sauvegarde) 49 | - [Désactiver la navigation de dossier](#désactiver-la-navigation-de-dossier) 50 | - [Désactiver le hotlink des images](#désactiver-le-hotlink-des-images) 51 | - [Désactiver le hotlink des images pour des domaines spécifiques](#désactiver-le-hotlink-des-images-pour-des-domaines-spécifiques) 52 | - [Protéger un dossier par mot de passe](#protéger-un-dossier-par-mot-de-passe) 53 | - [Protéger un ou plusieurs fichiers par mot de passe](#protéger-un-ou-plusieurs-fichiers-par-mot-de-passe) 54 | - [Performance](#performance) 55 | - [Compresser les fichiers texte](#compresser-les-fichiers-texte) 56 | - [Ajouter l'en-tête "Expires"](#ajouter-len-tête-expires) 57 | - [Désactiver eTags](#désactiver-etags) 58 | - [Divers](#divers) 59 | - [Définir des variables PHP](#définir-des-variables-php) 60 | - [Pages d'erreur personnalisées](#pages-derreur-personnalisées) 61 | - [Forcer le téléchargement](#forcer-le-téléchargement) 62 | - [Empêcher le téléchargement](#empêcher-le-téléchargement) 63 | - [Autoriser les polices Cross-Domain](#autoriser-les-polices-cross-domain) 64 | - [Encodage UTF-8 automatique](#encodage-utf-8-automatique) 65 | - [Basculer vers une autre version de PHP](#basculer-vers-une-autre-version-de-php) 66 | - [Désactiver le mode de compatibilité pour Internet Explorer](#désactiver-le-mode-de-compatibilité-pour-internet-explorer) 67 | - [Servir des images WebP](#servir-des-images-webp) 68 | 69 | 70 | ## Réécriture et redirection 71 | 72 | Remarque: On suppose avoir le module `mod_rewrite` installé et activé. 73 | 74 | 75 | ### Forcer www 76 | 77 | ``` apacheconf 78 | RewriteEngine on 79 | RewriteCond %{HTTP_HOST} ^example\.com [NC] 80 | RewriteRule ^(.*)$ http://www.example.com/$1 [L,R=301,NC] 81 | ``` 82 | 83 | 84 | ### Forcer www d'une manière générique 85 | 86 | ``` apacheconf 87 | RewriteCond %{HTTP_HOST} !^$ 88 | RewriteCond %{HTTP_HOST} !^www\. [NC] 89 | RewriteCond %{HTTPS}s ^on(s)| 90 | RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L] 91 | ``` 92 | 93 | Cela fonctionne pour _tous_ les domaines. 94 | [Source](https://stackoverflow.com/questions/4916222/htaccess-how-to-force-www-in-a-generic-way) 95 | 96 | 97 | ### Forcer non-www 98 | 99 | C'est [toujours](http://www.sitepoint.com/domain-www-or-no-www/) 100 | [en cours](https://devcenter.heroku.com/articles/apex-domains) 101 | [de](http://yes-www.org/) [débat](http://no-www.org/) selon s'il faut 102 | prévilégier la forme avec ou sans `www`, donc si vous êtes un fan de domaine 103 | "à nu", ceci est pour vous : 104 | 105 | ``` apacheconf 106 | RewriteEngine on 107 | RewriteCond %{HTTP_HOST} ^www\.example\.com [NC] 108 | RewriteRule ^(.*)$ http://example.com/$1 [L,R=301] 109 | ``` 110 | 111 | 112 | ### Forcer non-www d'une manière générique 113 | 114 | ``` apacheconf 115 | RewriteEngine on 116 | RewriteCond %{HTTP_HOST} ^www\. 117 | RewriteCond %{HTTPS}s ^on(s)|off 118 | RewriteCond http%1://%{HTTP_HOST} ^(https?://)(www\.)?(.+)$ 119 | RewriteRule ^ %1%3%{REQUEST_URI} [R=301,L] 120 | ``` 121 | 122 | 123 | ### Forcer HTTPS 124 | 125 | ``` apacheconf 126 | RewriteEngine on 127 | RewriteCond %{HTTPS} !on 128 | RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} 129 | ``` 130 | 131 | 132 | ### Forcer HTTPS derrière un proxy 133 | 134 | Ceci est utile si vous avez un proxy devant votre serveur faisant une 135 | termination TLS : 136 | 137 | ``` apacheconf 138 | RewriteCond %{HTTP:X-Forwarded-Proto} !https 139 | RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} 140 | ``` 141 | 142 | 143 | ### Forcer le slash de fin 144 | 145 | ``` apacheconf 146 | RewriteCond %{REQUEST_URI} /+[^\.]+$ 147 | RewriteRule ^(.+[^/])$ %{REQUEST_URI}/ [R=301,L] 148 | ``` 149 | 150 | 151 | ### Supprimer le slash de fin 152 | 153 | ``` apacheconf 154 | RewriteCond %{REQUEST_FILENAME} !-d 155 | RewriteRule ^(.*)/$ /$1 [R=301,L] 156 | ``` 157 | 158 | 159 | ### Rediriger une seule page 160 | 161 | ``` apacheconf 162 | Redirect 301 /anciennepage.html http://www.votresite.com/nouvellepage.html 163 | Redirect 301 /anciennepage2.html http://www.votresite.com/dossier/ 164 | ``` 165 | 166 | [Source](http://css-tricks.com/snippets/htaccess/301-redirects/) 167 | 168 | 169 | ### Alias pour un seul dossier 170 | 171 | ``` apacheconf 172 | RewriteEngine On 173 | RewriteRule ^source-directory/(.*) target-directory/$1 174 | ``` 175 | 176 | 177 | ### Alias de chemins vers un script 178 | 179 | ``` apacheconf 180 | FallbackResource /index.fcgi 181 | ``` 182 | 183 | Cet exemple a un fichier `index.fcgi` dans un répertoire, et toutes les requêtes 184 | à l'intérieur de ce dossier qui ne peuvent résoudre le fichier/dossier demandé 185 | seront renvoyées vers le script `index.fcgi`. Ceci est utile si vous souhaitez 186 | que `baz.foo/une/route/sympa` soit manipulé par `baz.foo/index.fcgi` (qui prend 187 | également en charge les demandes vers `baz.foo`) tout en maintenant 188 | `baz.foo/css/style.css` ou autre fonctionnels. Accédez au chemin d'origine de la 189 | variable d'environnement `PATH_INFO`, comme exposé à votre environnement de 190 | scriptage. 191 | 192 | ``` apacheconf 193 | RewriteEngine On 194 | RewriteRule ^$ index.fcgi/ [QSA,L] 195 | RewriteCond %{REQUEST_FILENAME} !-f 196 | RewriteCond %{REQUEST_FILENAME} !-d 197 | RewriteRule ^(.*)$ index.fcgi/$1 [QSA,L] 198 | ``` 199 | 200 | Ceci est une version moins efficace de la directive `FallbackResource` (car 201 | l'utilisation de `mod_rewrite` est plus complexe que de maintenir la directive 202 | `FallbackResource`), mais offre d'avantage de flexibilité. 203 | 204 | 205 | ### Rediriger un site entier 206 | 207 | ``` apacheconf 208 | Redirect 301 / http://nouveausite.com/ 209 | ``` 210 | 211 | Ceci laisse les liens intacts. Ainsi `anciensite.com/lien/super/genial.html` 212 | deviendra `nouveausite.com/lien/super/genial.html`. Cela est très pratique 213 | lorsque vous souhaitez déplacer un site vers un nouveau domaine. 214 | 215 | [Source](http://css-tricks.com/snippets/htaccess/301-redirects/) 216 | 217 | 218 | ### Alias en URLs propres 219 | 220 | Ce snippet vous permet d'utiliser des "URLs propres" –celles sans extension–, 221 | par exemple : `example.com/users` à la place de `example.com/users.php`. 222 | 223 | ``` apacheconf 224 | RewriteEngine On 225 | RewriteCond %{SCRIPT_FILENAME} !-d 226 | RewriteRule ^([^.]+)$ $1.php [NC,L] 227 | ``` 228 | 229 | [Source](http://www.abeautifulsite.net/access-pages-without-the-php-extension-using-htaccess/) 230 | 231 | 232 | ## Securité 233 | 234 | ### Refuser tout accès 235 | 236 | ``` apacheconf 237 | ## Apache 2.2 238 | Deny from all 239 | 240 | ## Apache 2.4 241 | # Require all denied 242 | ``` 243 | 244 | Mais… ceci vous bloquera vous également ! Si ce n'est pas ce que vous souhaitez, 245 | la partie suivante est sûrement faite pour vous ! 246 | 247 | 248 | ### Refuser tout accès sauf soi-même 249 | 250 | ``` apacheconf 251 | ## Apache 2.2 252 | Order deny,allow 253 | Deny from all 254 | Allow from xxx.xxx.xxx.xxx 255 | 256 | ## Apache 2.4 257 | # Require all denied 258 | # Require ip xxx.xxx.xxx.xxx 259 | ``` 260 | 261 | En remplaçant `xxx.xxx.xxx.xxx` par votre adresse IP, vous n'autoriserez l'accès 262 | à votre site que par vous. Si vous remplacez les 3 dernièrs numéros par `0/12` 263 | par exemple, ceci spécifiera un intervalle d'adresses IPs à l'intérieur d'un 264 | même réseau, vous évitant ainsi de lister toutes les IPs autorisées 265 | individuellement. 266 | 267 | [Source](http://speckyboy.com/2013/01/08/useful-htaccess-snippets-and-hacks/) 268 | 269 | Bien sûr, il y a la version inverse : 270 | 271 | 272 | ### Autoriser tout accès sauf aux spammeurs 273 | 274 | ``` apacheconf 275 | ## Apache 2.2 276 | Order deny,allow 277 | Deny from xxx.xxx.xxx.xxx 278 | Deny from xxx.xxx.xxx.xxy 279 | 280 | ## Apache 2.4 281 | # Require all granted 282 | # Require not ip xxx.xxx.xxx.xxx 283 | # Require not ip xxx.xxx.xxx.xxy 284 | ``` 285 | 286 | 287 | ### Refuser l'accès aux fichiers et dossiers cachés 288 | 289 | Les fichiers et dossiers cachés (ceux dont les noms commencent par un point `.`) 290 | devraient être pour la majorité d'entre eux sécurisés. On ne devrait par exemple 291 | pas avoir accès aux éléments suivants : `.htaccess`, `.htpasswd`, `.git`, 292 | `.hg`... 293 | 294 | ``` apacheconf 295 | RewriteCond %{SCRIPT_FILENAME} -d [OR] 296 | RewriteCond %{SCRIPT_FILENAME} -f 297 | RewriteRule "(^|/)\." - [F] 298 | ``` 299 | 300 | Une autre solution serait de lever une erreur `404 Not Found`, ne donnant aucun 301 | indice à l'attaquant quant à l'existance de la ressource : 302 | 303 | ``` apacheconf 304 | RedirectMatch 404 /\..*$ 305 | ``` 306 | 307 | 308 | ### Refuser l'accès aux sources et fichiers de sauvegarde 309 | 310 | Ces fichiers peuvent être laissés par certains éditeurs de texte/html (comme 311 | Vi/Vim) et poser un grand danger en terme de sécurité, quand quelqu'un y a 312 | accès. 313 | 314 | ``` apacheconf 315 | 316 | ## Apache 2.2 317 | Order allow,deny 318 | Deny from all 319 | Satisfy All 320 | 321 | ## Apache 2.4 322 | # Require all denied 323 | 324 | ``` 325 | 326 | [Source](https://github.com/h5bp/server-configs-apache) 327 | 328 | 329 | ### Désactiver la navigation de dossier 330 | 331 | ``` apacheconf 332 | Options All -Indexes 333 | ``` 334 | 335 | 336 | ### Désactiver le hotlink des images 337 | 338 | ``` apacheconf 339 | RewriteEngine on 340 | # Enlever la ligne ci-dessous si vous souhaitez bloquer le referrer vide 341 | RewriteCond %{HTTP_REFERER} !^$ 342 | 343 | RewriteCond %{HTTP_REFERER} !^http(s)?://(.+\.)?votredomaine.com [NC] 344 | RewriteRule \.(jpg|jpeg|png|gif|bmp)$ - [NC,F,L] 345 | 346 | # Si vous souhaitez afficher une bannière "Bloquée" d'url 'blocked.png' au lieu 347 | # du hotlink de l'image, replacez la règle ci-dessus par celle-ci : 348 | # RewriteRule \.(jpg|jpeg|png|gif|bmp) http://votredomaine.com/blocked.png [R,L] 349 | ``` 350 | 351 | 352 | ### Désactiver le hotlink des images pour des domaines spécifiques 353 | 354 | Parfois vous souhaitez désactiver le hotlink d'images seulement pour quelques 355 | domaines spécifiques. L'extrait suivant devrait vous aider : 356 | 357 | ``` apacheconf 358 | RewriteEngine on 359 | RewriteCond %{HTTP_REFERER} ^http(s)?://(.+\.)?mauvaissite\.com [NC,OR] 360 | RewriteCond %{HTTP_REFERER} ^http(s)?://(.+\.)?mauvaissite2\.com [NC,OR] 361 | RewriteRule \.(jpg|jpeg|png|gif)$ - [NC,F,L] 362 | 363 | # Si vous souhaitez afficher une bannière "Bloquée" d'url 'blocked.png' au lieu 364 | # du hotlink de l'image, replacez la règle ci-dessus par celle-ci : 365 | # RewriteRule \.(jpg|jpeg|png|gif|bmp) http://votredomaine.com/blocked.png [R,L] 366 | ``` 367 | 368 | 369 | ### Protéger un dossier par mot de passe 370 | 371 | D'abord, vous aurez besoin de créer un fichier `.htpasswd` quelque part sur le 372 | système, avec l'aide de la commande suivante : 373 | 374 | ``` bash 375 | htpasswd -c /home/fellowship/.htpasswd boromir 376 | ``` 377 | 378 | Ensuite, vous pouvez utiliser ceci pour activer l'authentification : 379 | 380 | ``` apacheconf 381 | AuthType Basic 382 | AuthName "One does not simply" 383 | AuthUserFile /home/fellowship/.htpasswd 384 | Require valid-user 385 | ``` 386 | 387 | 388 | ### Protéger un ou plusieurs fichiers par mot de passe 389 | 390 | ``` apacheconf 391 | AuthName "One still does not simply" 392 | AuthType Basic 393 | AuthUserFile /home/fellowship/.htpasswd 394 | 395 | 396 | Require valid-user 397 | 398 | 399 | 400 | Require valid-user 401 | 402 | ``` 403 | 404 | 405 | ## Performance 406 | 407 | ### Compresser les fichiers texte 408 | 409 | ``` apacheconf 410 | 411 | 412 | # Force compression for mangled headers. 413 | # https://developer.yahoo.com/blogs/ydn/pushing-beyond-gzipping-25601.html 414 | 415 | 416 | SetEnvIfNoCase ^(Accept-EncodXng|X-cept-Encoding|X{15}|~{15}|-{15})$ ^((gzip|deflate)\s*,?\s*)+|[X~-]{4,13}$ HAVE_Accept-Encoding 417 | RequestHeader append Accept-Encoding "gzip,deflate" env=HAVE_Accept-Encoding 418 | 419 | 420 | 421 | # Compresse toutes les sorties ayant un de ces types MIME 422 | # (pour Apache < 2.3.7, vous n'avez pas besoin d'activer `mod_filter` 423 | # et vous pouvez supprimer le `` et `` 424 | # comme `AddOutputFilterByType` sera toujours dans les directives du noyau). 425 | 426 | AddOutputFilterByType DEFLATE application/atom+xml \ 427 | application/javascript \ 428 | application/json \ 429 | application/rss+xml \ 430 | application/vnd.ms-fontobject \ 431 | application/x-font-ttf \ 432 | application/x-web-app-manifest+json \ 433 | application/xhtml+xml \ 434 | application/xml \ 435 | font/opentype \ 436 | image/svg+xml \ 437 | image/x-icon \ 438 | text/css \ 439 | text/html \ 440 | text/plain \ 441 | text/x-component \ 442 | text/xml 443 | 444 | 445 | 446 | ``` 447 | 448 | [Source](https://github.com/h5bp/server-configs-apache) 449 | 450 | 451 | ### Ajouter l'en-tête "Expires" 452 | 453 | L'en-tête *Expires* indique au navigateur s'il doit effectuer une requête au 454 | serveur pour récupérer un fichier spécifique ou bien se contenter du cache. On 455 | peut conseiller pour les contenus statiques un en-tête d'expiration loin dans le 456 | futur. 457 | 458 | Si vous n'utilisez pas la méthode du nom de fichier modifié par un système de 459 | contrôle de version, vous devriez diminuer le temps de cache des ressources 460 | telles que les fichiers CSS ou JS vers quelque chose proche de la semaine. 461 | 462 | ``` apacheconf 463 | 464 | ExpiresActive on 465 | ExpiresDefault "access plus 1 month" 466 | 467 | # CSS 468 | ExpiresByType text/css "access plus 1 year" 469 | 470 | # Data interchange 471 | ExpiresByType application/json "access plus 0 seconds" 472 | ExpiresByType application/xml "access plus 0 seconds" 473 | ExpiresByType text/xml "access plus 0 seconds" 474 | 475 | # Favicon (cannot be renamed!) 476 | ExpiresByType image/x-icon "access plus 1 week" 477 | 478 | # HTML components (HTCs) 479 | ExpiresByType text/x-component "access plus 1 month" 480 | 481 | # HTML 482 | ExpiresByType text/html "access plus 0 seconds" 483 | 484 | # JavaScript 485 | ExpiresByType application/javascript "access plus 1 year" 486 | 487 | # Manifest files 488 | ExpiresByType application/x-web-app-manifest+json "access plus 0 seconds" 489 | ExpiresByType text/cache-manifest "access plus 0 seconds" 490 | 491 | # Media 492 | ExpiresByType audio/ogg "access plus 1 month" 493 | ExpiresByType image/gif "access plus 1 month" 494 | ExpiresByType image/jpeg "access plus 1 month" 495 | ExpiresByType image/png "access plus 1 month" 496 | ExpiresByType video/mp4 "access plus 1 month" 497 | ExpiresByType video/ogg "access plus 1 month" 498 | ExpiresByType video/webm "access plus 1 month" 499 | 500 | # Web feeds 501 | ExpiresByType application/atom+xml "access plus 1 hour" 502 | ExpiresByType application/rss+xml "access plus 1 hour" 503 | 504 | # Web fonts 505 | ExpiresByType application/font-woff2 "access plus 1 month" 506 | ExpiresByType application/font-woff "access plus 1 month" 507 | ExpiresByType application/vnd.ms-fontobject "access plus 1 month" 508 | ExpiresByType application/x-font-ttf "access plus 1 month" 509 | ExpiresByType font/opentype "access plus 1 month" 510 | ExpiresByType image/svg+xml "access plus 1 month" 511 | 512 | ``` 513 | 514 | [Source](https://github.com/h5bp/server-configs-apache) 515 | 516 | 517 | ### Désactiver eTags 518 | 519 | En retirant l'en-tête "eTag", vous empêchez le cache et les navigateurs de 520 | pouvoir valider les fichiers, ils sont donc forcés de se baser sur le 521 | Cache-Control (contrôle de cache) et les Expires header (en-tête d'expiration). 522 | 523 | [Source](http://www.askapache.com/htaccess/apache-speed-etags.html) 524 | 525 | ``` apacheconf 526 | 527 | Header unset ETag 528 | 529 | FileETag None 530 | ``` 531 | 532 | 533 | ## Divers 534 | 535 | ### Définir des variables PHP 536 | 537 | ``` apacheconf 538 | php_value 539 | 540 | # Par exemple : 541 | php_value upload_max_filesize 50M 542 | php_value max_execution_time 240 543 | ``` 544 | 545 | 546 | ### Pages d'erreur personnalisées 547 | 548 | ``` apacheconf 549 | ErrorDocument 500 "Houston, on a un problème." 550 | ErrorDocument 401 http://error.votredomaine.com/mordor.html 551 | ErrorDocument 404 /errors/halflife3.html 552 | ``` 553 | 554 | 555 | ### Forcer le téléchargement 556 | 557 | Parfois, vous souhaitez forcer le navigateur à télécharger certaines ressources 558 | au lieu de les afficher. Le snippet suivant vous sera utile : 559 | 560 | ``` apacheconf 561 | 562 | ForceType application/octet-stream 563 | Header set Content-Disposition attachment 564 | 565 | ``` 566 | 567 | Si vous souhaitez l'action inverse : 568 | 569 | 570 | ### Empêcher le téléchargement 571 | 572 | Parfois, vous souhaitez forcer le navigateur à afficher certains contenus au 573 | lieu de les télécharger. Le snippet suivant devrait vous aider : 574 | 575 | ``` apacheconf 576 | 577 | Header set Content-Type text/plain 578 | 579 | ``` 580 | 581 | ### Autoriser les polices Cross-Domain 582 | 583 | Les polices desservies par un serveur CDN peuvent ne pas fonctionner sur Firefox 584 | ou IE à cause de 585 | [CORS](https://en.wikipedia.org/wiki/Cross-origin_resource_sharing). Le snippet 586 | suivant de [alrra](https://github.com/h5bp/server-configs-apache/issues/32) 587 | devrait corriger cela : 588 | 589 | ``` apacheconf 590 | 591 | 592 | Header set Access-Control-Allow-Origin "*" 593 | 594 | 595 | ``` 596 | 597 | ### Encodage UTF-8 automatique 598 | 599 | Votre contenu textuel devrait toujours être encodé en UTF-8, non ? 600 | 601 | ``` apacheconf 602 | # Utiliser l'encodage UTF-8 pour tout ce qui est servi en text/plain ou text/html 603 | AddDefaultCharset utf-8 604 | 605 | # Forcer l'UTF-8 pour certains formats de fichier 606 | AddCharset utf-8 .atom .css .js .json .rss .vtt .xml 607 | ``` 608 | 609 | [Source](https://github.com/h5bp/server-configs-apache) 610 | 611 | 612 | ### Basculer vers une autre version de PHP 613 | 614 | Si vous êtes sur un serveur mutualisé, il y a des chances pour qu'il y ait plus 615 | d'une version de PHP installée, et parfois, vous avez besoin d'une version 616 | spécifique pour votre site web. 617 | 618 | Par exemple [Laravel](https://github.com/laravel/laravel) nécessite PHP >= 5.4. 619 | Le snippet suivant devrait passer d'une version à l'autre de PHP pour vous : 620 | 621 | ``` apacheconf 622 | AddHandler application/x-httpd-php55 .php 623 | 624 | # Autrement, vous pouvez utiliser AddType 625 | AddType application/x-httpd-php55 .php 626 | ``` 627 | 628 | 629 | ### Désactiver le mode de compatibilité pour Internet Explorer 630 | 631 | Le mode de compatibilité dans IE peut affecter l'affichage de certains sites 632 | web. L'extrait suivant devrait forcer IE à utiliser le moteur d'interprétation 633 | Edge et ainsi désactiver le mode de compatibilité. 634 | 635 | ``` apacheconf 636 | 637 | BrowserMatch MSIE is-msie 638 | Header set X-UA-Compatible IE=edge env=is-msie 639 | 640 | ``` 641 | 642 | 643 | ### Servir des images WebP 644 | 645 | Si [WebP images](https://developers.google.com/speed/webp/?csw=1) est supporté 646 | et que l'image avec l'extension `.webp` a le même nom qu'une image jpg/png alors 647 | l'image Webp sera servie à la place. 648 | 649 | ``` apacheconf 650 | RewriteEngine On 651 | RewriteCond %{HTTP_ACCEPT} image/webp 652 | RewriteCond %{DOCUMENT_ROOT}/$1.webp -f 653 | RewriteRule (.+)\.(jpe?g|png)$ $1.webp [T=image/webp,E=accept:1] 654 | ``` 655 | 656 | [Source](https://github.com/vincentorback/WebP-images-with-htaccess) 657 | -------------------------------------------------------------------------------- /Translations/German/README.md: -------------------------------------------------------------------------------- 1 | # .htaccess-Ausschnitte 2 | Eine Sammlung nützlicher .htaccess-Ausschnitte, alle an einem Ort. 3 | 4 | **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. 5 | 6 | **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. 7 | 8 | ## Danksagungen 9 | 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. 10 | 11 | ## Inhalt 12 | - [Umschreibung und Weiterleitung](#umschreibung-und-weiterleitung) 13 | - [www erzwingen](#www-erzwingen) 14 | - [www allgemein erzwingen](#www-allgemein-erzwingen) 15 | - [nicht-www erzwingen](#nicht-www-erzwingen) 16 | - [nicht-www allgemein erzwingen](#nicht-www-allgemein-erzwingen) 17 | - [HTTPS erzwingen](#https-erzwingen) 18 | - [HTTPS hinter einem Proxy erzwingen](#https-hinter-einem-proxy-erzwingen) 19 | - [Abschließende Querstriche erzwingen](#abschlie%C3%9Fende-querstriche-erzwingen) 20 | - [Abschließende Querstriche entfernen](#abschlie%C3%9Fende-querstriche-entfernen) 21 | - [Eine einzelne Seite weiterleiten](#eine-einzelne-seite-weiterleiten) 22 | - [Alias für ein einzelnes Verzeichnis hinzufügen](#alias-f%C3%BCr-ein-einzelnes-verzeichnis-hinzuf%C3%BCgen) 23 | - [Verzeichnisalias für ein Skript hinzufügen](#verzeichnisalias-f%C3%BCr-ein-skript-hinzuf%C3%BCgen) 24 | - [Eine komplette Seite weiterleiten](#eine-komplette-seite-weiterleiten) 25 | - [Alias für "saubere" URLs hinzufügen](#alias-f%C3%BCr-saubere-urls-hinzuf%C3%BCgen) 26 | - [Sicherheit](#sicherheit) 27 | - [Kompletten Zugriff verbieten](#kompletten-zugriff-verbieten) 28 | - [Kompletten Zugriff außer Ihren verbieten](#kompletten-zugriff-au%C3%9Fer-ihren-verbieten) 29 | - [Zugriff erlauben, außer von Spammern](#zugriff-erlauben-au%C3%9Fer-von-spammern) 30 | - [Zugriff zu versteckten Dateien und Verzeichnissen verbieten](#zugriff-zu-versteckten-dateien-und-verzeichnissen-verbieten) 31 | - [Zugriff zu Backup- und Quelldateien verbieten](#zugriff-zu-backup--und-quelldateien-verbieten) 32 | - [Verzeichnis-Auflistung abschalten](#verzeichnis-auflistung-abschalten) 33 | - [Bild-Hotlinking abschalten](#bild-hotlinking-abschalten) 34 | - [Bild-Hotlinking für spezielle Domains abschalten](#bild-hotlinking-f%C3%BCr-spezielle-domains-abschalten) 35 | - [Ein Verzeichnis mit Passwort schützen](#ein-verzeichnis-mit-passwort-sch%C3%BCtzen) 36 | - [Eine oder mehrere Dateien mit Passwort schützen](#eine-oder-mehrere-dateien-mit-passwort-sch%C3%BCtzen) 37 | - [Besucher nach Referrer blockieren](#besucher-nach-referrer-blockieren) 38 | - [Verbieten, die Seite in Frames zu verwenden](#verbieten-die-seite-in-frames-zu-verwenden) 39 | - [Leistung](#leistung) 40 | - [Textdateien komprimieren](#textdateien-komprimieren) 41 | - [Ablaufdatum im Header setzen](#ablaufdatum-im-header-setzen) 42 | - [eTags abschalten](#etags-abschalten) 43 | - [Verschiedenes](#verschiedenes) 44 | - [PHP Variablen setzen](#php-variablen-setzen) 45 | - [Eigene Fehlerseiten](#eigene-fehlerseiten) 46 | - [Download erzwingen](#download-erzwingen) 47 | - [Download verhindern](#download-verhindern) 48 | - [Domainübergreifende Schriftarten erlauben](#domain%C3%BCbergreifende-schriftarten-erlauben) 49 | - [Automatische UTF-8-Kodierung](#automatische-utf-8-kodierung) 50 | - [Zu einer anderen PHP-Version wechseln](#zu-einer-anderen-php-version-wechseln) 51 | - [Kompatibilitätsansicht des Internet Explorer deaktivieren](#kompatibilit%C3%A4tsansicht-des-internet-explorer-deaktivieren) 52 | - [WebP-Bilder bereitstellen](#webp-bilder-bereitstellen) 53 | 54 | ## Umschreibung und Weiterleitung 55 | Anmerkung: Es wird vorausgesetzt, dass Sie `mod_rewrite` installiert und aktiviert haben. 56 | 57 | ### www erzwingen 58 | ``` apacheconf 59 | RewriteEngine on 60 | RewriteCond %{HTTP_HOST} ^example\.com [NC] 61 | RewriteRule ^(.*)$ http://www.example.com/$1 [L,R=301,NC] 62 | ``` 63 | 64 | ### www allgemein erzwingen 65 | ``` apacheconf 66 | RewriteCond %{HTTP_HOST} !^$ 67 | RewriteCond %{HTTP_HOST} !^www\. [NC] 68 | RewriteCond %{HTTPS}s ^on(s)| 69 | RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L] 70 | ``` 71 | Dies funktioniert für _jede_ Domain. [Quelle](https://stackoverflow.com/questions/4916222/htaccess-how-to-force-www-in-a-generic-way) 72 | 73 | ### nicht-www erzwingen 74 | 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: 75 | ``` apacheconf 76 | RewriteEngine on 77 | RewriteCond %{HTTP_HOST} ^www\.example\.com [NC] 78 | RewriteRule ^(.*)$ http://example.com/$1 [L,R=301] 79 | ``` 80 | 81 | ### nicht-www allgemein erzwingen 82 | ``` apacheconf 83 | RewriteEngine on 84 | RewriteCond %{HTTP_HOST} ^www\. 85 | RewriteCond %{HTTPS}s ^on(s)|off 86 | RewriteCond http%1://%{HTTP_HOST} ^(https?://)(www\.)?(.+)$ 87 | RewriteRule ^ %1%3%{REQUEST_URI} [R=301,L] 88 | ``` 89 | 90 | ### HTTPS erzwingen 91 | ``` apacheconf 92 | RewriteEngine on 93 | RewriteCond %{HTTPS} !on 94 | RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} 95 | 96 | # Bemerkung: Es wird außerdem empfohlen, HTTP Strict Transport Security (HSTS) 97 | # auf Ihrer HTTPS-Webseite zu aktivieren, um Man-in-the-Middle-Attacken zu vermeiden. 98 | # Siehe https://developer.mozilla.org/en-US/docs/Web/Security/HTTP_strict_transport_security 99 | 100 | Header always set Strict-Transport-Security "max-age=31536000; includeSubDomains" 101 | 102 | ``` 103 | 104 | ### HTTPS hinter einem Proxy erzwingen 105 | Nützlich, wenn Sie einen Proxy vor Ihrem Server haben, der TLS-Termination ausführt. 106 | ``` apacheconf 107 | RewriteCond %{HTTP:X-Forwarded-Proto} !https 108 | RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} 109 | ``` 110 | 111 | ### Abschließende Querstriche erzwingen 112 | ``` apacheconf 113 | RewriteCond %{REQUEST_URI} /+[^\.]+$ 114 | RewriteRule ^(.+[^/])$ %{REQUEST_URI}/ [R=301,L] 115 | ``` 116 | 117 | ### Abschließende Querstriche entfernen 118 | ``` apacheconf 119 | RewriteCond %{REQUEST_FILENAME} !-d 120 | RewriteRule ^(.*)/$ /$1 [R=301,L] 121 | ``` 122 | ### Eine einzelne Seite weiterleiten 123 | ``` apacheconf 124 | Redirect 301 /oldpage.html http://www.example.com/newpage.html 125 | Redirect 301 /oldpage2.html http://www.example.com/folder/ 126 | ``` 127 | [Quelle](http://css-tricks.com/snippets/htaccess/301-redirects/) 128 | 129 | ### Alias für ein einzelnes Verzeichnis hinzufügen 130 | ``` apacheconf 131 | RewriteEngine On 132 | RewriteRule ^source-directory/(.*) target-directory/$1 133 | ``` 134 | 135 | ### Verzeichnisalias für ein Skript hinzufügen 136 | ``` apacheconf 137 | FallbackResource /index.fcgi 138 | ``` 139 | 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. 140 | 141 | ``` apacheconf 142 | RewriteEngine On 143 | RewriteRule ^$ index.fcgi/ [QSA,L] 144 | RewriteCond %{REQUEST_FILENAME} !-f 145 | RewriteCond %{REQUEST_FILENAME} !-d 146 | RewriteRule ^(.*)$ index.fcgi/$1 [QSA,L] 147 | ``` 148 | 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. 149 | 150 | ### Eine komplette Seite weiterleiten 151 | ``` apacheconf 152 | Redirect 301 / http://newsite.com/ 153 | ``` 154 | 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/) 155 | 156 | ### Alias für "saubere" URLs hinzufügen 157 | Dieser Ausschnitt erlaubt Ihnen, "saubere URLs", also URLs ohne Dateinamenserweiterung, beispielsweise `example.com/users` anstelle von `example.com/users.php` zu verwenden. 158 | ``` apacheconf 159 | RewriteEngine On 160 | RewriteCond %{SCRIPT_FILENAME} !-d 161 | RewriteRule ^([^.]+)$ $1.php [NC,L] 162 | ``` 163 | [Quelle](http://www.abeautifulsite.net/access-pages-without-the-php-extension-using-htaccess/) 164 | 165 | ## Sicherheit 166 | ### Kompletten Zugriff verbieten 167 | ``` apacheconf 168 | ## Apache 2.2 169 | Deny from all 170 | 171 | ## Apache 2.4 172 | # Require all denied 173 | ``` 174 | 175 | Achtung, dadurch werden alle Benutzer, auch Sie selbst, von der Webseite ausgesperrt. 176 | 177 | ### Kompletten Zugriff außer Ihren verbieten 178 | ``` apacheconf 179 | ## Apache 2.2 180 | Order deny,allow 181 | Deny from all 182 | Allow from xxx.xxx.xxx.xxx 183 | 184 | ## Apache 2.4 185 | # Require all denied 186 | # Require ip xxx.xxx.xxx.xxx 187 | ``` 188 | `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/) 189 | 190 | Natürlich gibt es auch eine umgekehrte Version: 191 | 192 | ### Zugriff erlauben, außer von Spammern 193 | ``` apacheconf 194 | ## Apache 2.2 195 | Order deny,allow 196 | Deny from xxx.xxx.xxx.xxx 197 | Deny from xxx.xxx.xxx.xxy 198 | 199 | ## Apache 2.4 200 | # Require all granted 201 | # Require not ip xxx.xxx.xxx.xxx 202 | # Require not ip xxx.xxx.xxx.xxy 203 | ``` 204 | 205 | ### Zugriff zu versteckten Dateien und Verzeichnissen verbieten 206 | Versteckte Dateien und Verzeichnisse (die, deren Name mit einem Punkt `.` startet) sollen meistens, wenn nicht immer, abgesichert werden. Zum Beispiel: `.htaccess`, `.htpasswd`, `.git`, `.hg`... 207 | ``` apacheconf 208 | RewriteCond %{SCRIPT_FILENAME} -d [OR] 209 | RewriteCond %{SCRIPT_FILENAME} -f 210 | RewriteRule "(^|/)\." - [F] 211 | ``` 212 | 213 | Alternativ können Sie auch einen `Not Found`-Fehler ausgeben, damit der Angreifer keinen Hinweis auf die Existenz der Dateien erhält: 214 | ``` apacheconf 215 | RedirectMatch 404 /\..*$ 216 | ``` 217 | 218 | ### Zugriff zu Backup- und Quelldateien verbieten 219 | 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. 220 | ``` apacheconf 221 | 222 | ## Apache 2.2 223 | Order allow,deny 224 | Deny from all 225 | Satisfy All 226 | 227 | ## Apache 2.4 228 | # Require all denied 229 | 230 | ``` 231 | [Quelle](https://github.com/h5bp/server-configs-apache) 232 | 233 | ### Verzeichnis-Auflistung abschalten 234 | ``` apacheconf 235 | Options All -Indexes 236 | ``` 237 | 238 | ### Bild-Hotlinking abschalten 239 | ``` apacheconf 240 | RewriteEngine on 241 | # Entfernen Sie die folgende Zeile, wenn Sie auch Anfragen mit leerem Referrer blockieren möchten 242 | RewriteCond %{HTTP_REFERER} !^$ 243 | 244 | RewriteCond %{HTTP_REFERER} !^http(s)?://(.+\.)?example.com [NC] 245 | RewriteRule \.(jpg|jpeg|png|gif|bmp)$ - [NC,F,L] 246 | 247 | # Wenn Sie einen "Blockiert"-Banner anstatt des gehotlinkten Bildes 248 | # anzeigen möchten, ersetzen Sie die obere Regel mit: 249 | # RewriteRule \.(jpg|jpeg|png|gif|bmp) http://example.com/blocked.png [R,L] 250 | ``` 251 | 252 | ### Bild-Hotlinking für spezielle Domains abschalten 253 | Manchmal möchte man Bild-Hotlinking nur für manche Seiten deaktivieren. 254 | ``` apacheconf 255 | RewriteEngine on 256 | RewriteCond %{HTTP_REFERER} ^http(s)?://(.+\.)?badsite\.com [NC,OR] 257 | RewriteCond %{HTTP_REFERER} ^http(s)?://(.+\.)?badsite2\.com [NC,OR] 258 | RewriteRule \.(jpg|jpeg|png|gif)$ - [NC,F,L] 259 | 260 | # Wenn Sie einen "Blockiert"-Banner anstatt des gehotlinkten Bildes 261 | # anzeigen möchten, ersetzen Sie die obere Regel mit: 262 | # RewriteRule \.(jpg|jpeg|png|gif|bmp) http://example.com/blocked.png [R,L] 263 | ``` 264 | 265 | ### Ein Verzeichnis mit Passwort schützen 266 | Zuerst müssen Sie irgendwo eine `.htpasswd`-Datei erstellen: 267 | ``` bash 268 | htpasswd -c /home/fellowship/.htpasswd boromir 269 | ``` 270 | 271 | Dann können Sie diese zur Authentifizierung benutzen: 272 | ``` apacheconf 273 | AuthType Basic 274 | AuthName "One does not simply" 275 | AuthUserFile /home/fellowship/.htpasswd 276 | Require valid-user 277 | ``` 278 | 279 | ### Eine oder mehrere Dateien mit Passwort schützen 280 | ``` apacheconf 281 | AuthName "One still does not simply" 282 | AuthType Basic 283 | AuthUserFile /home/fellowship/.htpasswd 284 | 285 | 286 | Require valid-user 287 | 288 | 289 | 290 | Require valid-user 291 | 292 | ``` 293 | 294 | ### Besucher nach Referrer blockieren 295 | Verbietet den Zugriff für alle Benutzer, die von einer bestimmten Domain weitergeleitet wurden. 296 | [Quelle](http://www.htaccess-guide.com/deny-visitors-by-referrer/) 297 | ``` apacheconf 298 | RewriteEngine on 299 | # Options +FollowSymlinks 300 | RewriteCond %{HTTP_REFERER} somedomain\.com [NC,OR] 301 | RewriteCond %{HTTP_REFERER} anotherdomain\.com 302 | RewriteRule .* - [F] 303 | ``` 304 | 305 | ### Verbieten, die Seite in Frames zu verwenden 306 | 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. 307 | ``` apacheconf 308 | SetEnvIf Request_URI "/starry-night" allow_framing=true 309 | Header set X-Frame-Options SAMEORIGIN env=!allow_framing 310 | ``` 311 | 312 | ## Leistung 313 | ### Textdateien komprimieren 314 | ``` apacheconf 315 | 316 | 317 | # Kompression für verstümmelte Header erzwingen. 318 | # https://developer.yahoo.com/blogs/ydn/pushing-beyond-gzipping-25601.html 319 | 320 | 321 | SetEnvIfNoCase ^(Accept-EncodXng|X-cept-Encoding|X{15}|~{15}|-{15})$ ^((gzip|deflate)\s*,?\s*)+|[X~-]{4,13}$ HAVE_Accept-Encoding 322 | RequestHeader append Accept-Encoding "gzip,deflate" env=HAVE_Accept-Encoding 323 | 324 | 325 | 326 | # Alles mit den folgenden MIME-Typen komprimieren: 327 | # (für Apache-Versionen unter 2.3.7, müssen Sie `mod_filter` nicht aktivieren 328 | # und können die Zeilen `` und `` entfernen 329 | # da `AddOutputFilterByType` noch immer in den Hauptdirektiven ist). 330 | 331 | AddOutputFilterByType DEFLATE application/atom+xml \ 332 | application/javascript \ 333 | application/json \ 334 | application/rss+xml \ 335 | application/vnd.ms-fontobject \ 336 | application/x-font-ttf \ 337 | application/x-web-app-manifest+json \ 338 | application/xhtml+xml \ 339 | application/xml \ 340 | font/opentype \ 341 | image/svg+xml \ 342 | image/x-icon \ 343 | text/css \ 344 | text/html \ 345 | text/plain \ 346 | text/x-component \ 347 | text/xml 348 | 349 | 350 | 351 | ``` 352 | [Quelle](https://github.com/h5bp/server-configs-apache) 353 | 354 | 355 | ### Ablaufdatum im Header setzen 356 | _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. 357 | 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) 358 | ``` apacheconf 359 | 360 | ExpiresActive on 361 | ExpiresDefault "access plus 1 month" 362 | 363 | # CSS 364 | ExpiresByType text/css "access plus 1 year" 365 | 366 | # Datenaustausch 367 | ExpiresByType application/json "access plus 0 seconds" 368 | ExpiresByType application/xml "access plus 0 seconds" 369 | ExpiresByType text/xml "access plus 0 seconds" 370 | 371 | # Favicon (kann nicht umbenannt werden!) 372 | ExpiresByType image/x-icon "access plus 1 week" 373 | 374 | # HTML-Komponenten (HTCs) 375 | ExpiresByType text/x-component "access plus 1 month" 376 | 377 | # HTML 378 | ExpiresByType text/html "access plus 0 seconds" 379 | 380 | # JavaScript 381 | ExpiresByType application/javascript "access plus 1 year" 382 | 383 | # Manifestdateien 384 | ExpiresByType application/x-web-app-manifest+json "access plus 0 seconds" 385 | ExpiresByType text/cache-manifest "access plus 0 seconds" 386 | 387 | # Medien 388 | ExpiresByType audio/ogg "access plus 1 month" 389 | ExpiresByType image/gif "access plus 1 month" 390 | ExpiresByType image/jpeg "access plus 1 month" 391 | ExpiresByType image/png "access plus 1 month" 392 | ExpiresByType video/mp4 "access plus 1 month" 393 | ExpiresByType video/ogg "access plus 1 month" 394 | ExpiresByType video/webm "access plus 1 month" 395 | 396 | # Web-Feeds 397 | ExpiresByType application/atom+xml "access plus 1 hour" 398 | ExpiresByType application/rss+xml "access plus 1 hour" 399 | 400 | # Web-Schriftarten 401 | ExpiresByType application/font-woff2 "access plus 1 month" 402 | ExpiresByType application/font-woff "access plus 1 month" 403 | ExpiresByType application/vnd.ms-fontobject "access plus 1 month" 404 | ExpiresByType application/x-font-ttf "access plus 1 month" 405 | ExpiresByType font/opentype "access plus 1 month" 406 | ExpiresByType image/svg+xml "access plus 1 month" 407 | 408 | ``` 409 | 410 | ### eTags abschalten 411 | 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) 412 | ``` apacheconf 413 | 414 | Header unset ETag 415 | 416 | FileETag None 417 | ``` 418 | 419 | ## Verschiedenes 420 | 421 | ### PHP-Variablen setzen 422 | ``` apacheconf 423 | php_value 424 | 425 | # Zum Beispiel: 426 | php_value upload_max_filesize 50M 427 | php_value max_execution_time 240 428 | ``` 429 | 430 | ### Eigene Fehlerseiten 431 | ``` apacheconf 432 | ErrorDocument 500 "Houston, wir haben ein Problem." 433 | ErrorDocument 401 http://error.example.com/mordor.html 434 | ErrorDocument 404 /errors/halflife3.html 435 | ``` 436 | 437 | ### Download erzwingen 438 | Manchmal möchten Sie den Browser dazu zwingen, Inhalte herunterzuladen, anstatt sie nur anzuzeigen. 439 | ``` apacheconf 440 | 441 | ForceType application/octet-stream 442 | Header set Content-Disposition attachment 443 | 444 | ``` 445 | 446 | Es gibt auch ein Yang zu diesem Yin: 447 | 448 | ### Download verhindern 449 | Manchmal möchten Sie den Browser dazu zwingen, Inhalte nur anzuzeigen, anstatt sie herunterzuladen. 450 | ``` apacheconf 451 | 452 | Header set Content-Type text/plain 453 | 454 | ``` 455 | 456 | ### Domainübergreifende Schriftarten erlauben 457 | 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. 458 | ``` apacheconf 459 | 460 | 461 | Header set Access-Control-Allow-Origin "*" 462 | 463 | 464 | ``` 465 | [Quelle](https://github.com/h5bp/server-configs-apache/issues/32) 466 | 467 | ### Automatische UTF-8-Kodierung 468 | Häufig ist es wünschenswert, dass Text immer als UTF-8 kodiert wird. 469 | ``` apacheconf 470 | # UTF-8-Kodierung für alles verwenden, was als text/plain oder text/html angeboten wird 471 | AddDefaultCharset utf-8 472 | 473 | # UTF-8-Kodierung für bestimmte Dateitypen erzwingen 474 | AddCharset utf-8 .atom .css .js .json .rss .vtt .xml 475 | ``` 476 | [Quelle](https://github.com/h5bp/server-configs-apache) 477 | 478 | ### Zu einer anderen PHP-Version wechseln 479 | 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. 480 | 481 | ``` apacheconf 482 | AddHandler application/x-httpd-php55 .php 483 | 484 | # Alternativ können Sie AddType benutzen 485 | AddType application/x-httpd-php55 .php 486 | ``` 487 | 488 | ### Kompatibilitätsansicht des Internet Explorer deaktivieren 489 | 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. 490 | 491 | ``` apacheconf 492 | 493 | BrowserMatch MSIE is-msie 494 | Header set X-UA-Compatible IE=edge env=is-msie 495 | 496 | ``` 497 | 498 | ### WebP-Bilder bereitstellen 499 | 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. 500 | 501 | ``` apacheconf 502 | RewriteEngine On 503 | RewriteCond %{HTTP_ACCEPT} image/webp 504 | RewriteCond %{DOCUMENT_ROOT}/$1.webp -f 505 | RewriteRule (.+)\.(jpe?g|png)$ $1.webp [T=image/webp,E=accept:1] 506 | ``` 507 | [Quelle](https://github.com/vincentorback/WebP-images-with-htaccess) 508 | -------------------------------------------------------------------------------- /Translations/Italian/README.md: -------------------------------------------------------------------------------- 1 | # .htaccess Snippets [![Awesome](https://cdn.rawgit.com/sindresorhus/awesome/d7305f38d29fed78fa85652e3a63e154dd8e8829/media/badge.svg)](https://github.com/sindresorhus/awesome) 2 | Una collezione di esempi utili di .htaccess. 3 | 4 | **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. 5 | 6 | **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). 7 | 8 | ## Riconoscimenti 9 | 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. 10 | 11 | ## Sommario 12 | - [Rewrite e Redirection](#rewrite-and-redirection) 13 | - [Forza www](#force-www) 14 | - [Forza www in maniera generica](#force-www-in-a-generic-way) 15 | - [Forza non-www](#force-non-www) 16 | - [Forza non-www in maniera generica](#force-non-www-in-a-generic-way) 17 | - [Forza HTTPS](#force-https) 18 | - [Forza HTTPS se dietro Proxy](#force-https-behind-a-proxy) 19 | - [Forza lo Slash finale](#force-trailing-slash) 20 | - [Rimuovi lo Slash finale](#remove-trailing-slash) 21 | - [Rimuovi lo Slash finale da percorsi arbitrari](#remove-trailing-slash-from-arbitrary-paths) 22 | - [Redireziona una singola pagina](#redirect-a-single-page) 23 | - [Alias a singole Cartelle](#alias-a-single-directory) 24 | - [Percorsi Alias a Script](#alias-paths-to-script) 25 | - [Redireziona un Intero Sito](#redirect-an-entire-site) 26 | - [Alias per URL "Pulite"](#alias-clean-urls) 27 | - [Sicurezza](#security) 28 | - [Nega tutti gli accessi](#deny-all-access) 29 | - [Nega l'accesso a tutti tranne per te stesso](#deny-all-access-except-yours) 30 | - [Permetti a tutti l'accesso tranne agli Spammer](#allow-all-access-except-spammers) 31 | - [Nega l'accesso a Cartelle e File Nascosti](#deny-access-to-hidden-files-and-directories) 32 | - [Nega l'accesso a Backup e File Sorgenti](#deny-access-to-backup-and-source-files) 33 | - [Disabilita l'Esplorazione delle Cartelle](#disable-directory-browsing) 34 | - [Disabilita Hotlinking delle Immagini](#disable-image-hotlinking) 35 | - [Disabilita Hotlinking delle Immagini per Domini Specifici](#disable-image-hotlinking-for-specific-domains) 36 | - [Proteggi una Cartella con Password](#password-protect-a-directory) 37 | - [Proteggi uno o più file con Password](#password-protect-a-file-or-several-files) 38 | - [Blocca i visitatori in base al Referrer](#block-visitors-by-referrer) 39 | - [Previeni l'inclusione del Sito tramite frame (framing)](#prevent-framing-the-site) 40 | - [Prestazioni](#performance) 41 | - [Comprimi i File di Testo](#compress-text-files) 42 | - [Imposta header expires](#set-expires-headers) 43 | - [Disabilita gli eTags](#turn-etags-off) 44 | - [Miscellanea](#miscellaneous) 45 | - [Imposta variabili PHP](#set-php-variables) 46 | - [Pagine di Errore Personalizzate](#custom-error-pages) 47 | - [Forza il Download](#force-downloading) 48 | - [Previeni il Download](#prevent-downloading) 49 | - [Permetti i Web Font da domini differenti](#allow-cross-domain-fonts) 50 | - [Codifica automaticamente in UTF-8](#auto-utf-8-encode) 51 | - [Passa a una versione diversa di PHP](#switch-to-another-php-version) 52 | - [Disabilita Visualizzazione Compatibilità di Internet Explorer](#disable-internet-explorer-compatibility-view) 53 | - [Rendere disponibili immagini in formato WebP](#serve-webp-images) 54 | 55 | ## Rewrite e Redirection 56 | Nota: Si presume che `mod_rewrite` sia installato e abilitato. 57 | 58 | ### Forza www 59 | ``` apacheconf 60 | RewriteEngine on 61 | RewriteCond %{HTTP_HOST} ^esempio\.com [NC] 62 | RewriteRule ^(.*)$ http://www.esempio.com/$1 [L,R=301,NC] 63 | ``` 64 | 65 | ### Forza www in maniera generica 66 | ``` apacheconf 67 | RewriteCond %{HTTP_HOST} !^$ 68 | RewriteCond %{HTTP_HOST} !^www\. [NC] 69 | RewriteCond %{HTTPS}s ^on(s)| 70 | RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L] 71 | ``` 72 | Funziona per _qualsiasi_ dominio. [Sorgente](https://stackoverflow.com/questions/4916222/htaccess-how-to-force-www-in-a-generic-way) 73 | 74 | ### Forza non-www 75 | 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: 76 | ``` apacheconf 77 | RewriteEngine on 78 | RewriteCond %{HTTP_HOST} ^www\.esempio\.com [NC] 79 | RewriteRule ^(.*)$ http://esempio.com/$1 [L,R=301] 80 | ``` 81 | 82 | ### Forza non-www in maniera generica 83 | ``` apacheconf 84 | RewriteEngine on 85 | RewriteCond %{HTTP_HOST} ^www\. 86 | RewriteCond %{HTTPS}s ^on(s)|off 87 | RewriteCond http%1://%{HTTP_HOST} ^(https?://)(www\.)?(.+)$ 88 | RewriteRule ^ %1%3%{REQUEST_URI} [R=301,L] 89 | ``` 90 | 91 | ### Forza HTTPS 92 | ``` apacheconf 93 | RewriteEngine on 94 | RewriteCond %{HTTPS} !on 95 | RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} 96 | 97 | # Nota: Si consiglia di abilitare anche HTTP Strict Transport Security (HSTS) 98 | # sul sito HTTPS per aiutare a prevenire attacchi man-in-the-middle. 99 | # Vedere https://developer.mozilla.org/en-US/docs/Web/Security/HTTP_strict_transport_security 100 | 101 | Header always set Strict-Transport-Security "max-age=31536000; includeSubDomains" 102 | 103 | ``` 104 | 105 | ### Forza HTTPS se dietro Proxy 106 | Utile se hai un proxy con TLS prima del tuo server. 107 | ``` apacheconf 108 | RewriteCond %{HTTP:X-Forwarded-Proto} !https 109 | RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} 110 | ``` 111 | 112 | ### Forza Slash Finale 113 | ``` apacheconf 114 | RewriteCond %{REQUEST_URI} /+[^\.]+$ 115 | RewriteRule ^(.+[^/])$ %{REQUEST_URI}/ [R=301,L] 116 | ``` 117 | 118 | ### Rimuovi Slash Finale 119 | ``` apacheconf 120 | RewriteCond %{REQUEST_FILENAME} !-d 121 | RewriteRule ^(.*)/$ /$1 [R=301,L] 122 | ``` 123 | 124 | ### Rimuovi Slash Finale da percorsi arbitrari 125 | 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. 126 | ``` apacheconf 127 | RewriteCond %{REQUEST_FILENAME} !-d 128 | RewriteCond %{REQUEST_URI} (.+)/$ 129 | RewriteRule ^ %1 [L,R=301] 130 | ``` 131 | [Sorgente](https://stackoverflow.com/questions/21417263/htaccess-add-remove-trailing-slash-from-url#27264788) 132 | 133 | ### Redireziona una singola pagina 134 | ``` apacheconf 135 | Redirect 301 /vecchiapagina.html http://www.esempio.com/nuovapagina.html 136 | Redirect 301 /vecchiapagina2.html http://www.esempio.com/cartella/ 137 | ``` 138 | [Sorgente](http://css-tricks.com/snippets/htaccess/301-redirects/) 139 | 140 | ### Alias di una singola Cartella 141 | ``` apacheconf 142 | RewriteEngine On 143 | RewriteRule ^source-directory/(.*) /target-directory/$1 [R=301,L] 144 | ``` 145 | 146 | ### Percorsi Alias a Script 147 | ``` apacheconf 148 | FallbackResource /index.fcgi 149 | ``` 150 | 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. 151 | 152 | ``` apacheconf 153 | RewriteEngine On 154 | RewriteRule ^$ index.fcgi/ [QSA,L] 155 | RewriteCond %{REQUEST_FILENAME} !-f 156 | RewriteCond %{REQUEST_FILENAME} !-d 157 | RewriteRule ^(.*)$ index.fcgi/$1 [QSA,L] 158 | ``` 159 | 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. 160 | 161 | ### Redireziona un intero sito 162 | ``` apacheconf 163 | Redirect 301 / http://nuovosito.com/ 164 | ``` 165 | 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/) 166 | 167 | ### Alias per URL "Pulite" 168 | Questo esempio ti permette di utilizzare URL "pulite" -- URL senza estensione PHP. es. `esempio.com/utenti` invece di `esempio.com/utenti.php`. 169 | ``` apacheconf 170 | RewriteEngine On 171 | RewriteCond %{SCRIPT_FILENAME} !-d 172 | RewriteRule ^([^.]+)$ $1.php [NC,L] 173 | ``` 174 | [Sorgente](http://www.abeautifulsite.net/access-pages-without-the-php-extension-using-htaccess/) 175 | 176 | ## Sicurezza 177 | ### Nega tutti gli Accessi 178 | ``` apacheconf 179 | ## Apache 2.2 180 | Deny from all 181 | 182 | ## Apache 2.4 183 | # Require all denied 184 | ``` 185 | 186 | In questa maniera rimarrai escluso anche tu dai tui contenuti! Per questo introduciamo... 187 | 188 | ### Nega l'accesso a tutti tranne per te stesso 189 | ``` apacheconf 190 | ## Apache 2.2 191 | Order deny,allow 192 | Deny from all 193 | Allow from xxx.xxx.xxx.xxx 194 | 195 | ## Apache 2.4 196 | # Require all denied 197 | # Require ip xxx.xxx.xxx.xxx 198 | ``` 199 | `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/) 200 | 201 | Ecco la versione al contrario: 202 | 203 | ### Permetti a tutti gli accessi tranne agli Spammer 204 | ``` apacheconf 205 | ## Apache 2.2 206 | Order deny,allow 207 | Deny from xxx.xxx.xxx.xxx 208 | Deny from xxx.xxx.xxx.xxy 209 | 210 | ## Apache 2.4 211 | # Require all granted 212 | # Require not ip xxx.xxx.xxx.xxx 213 | # Require not ip xxx.xxx.xxx.xxy 214 | ``` 215 | 216 | ### Nega l'accesso a Cartelle e File Nascosti 217 | 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`... 218 | ``` apacheconf 219 | RewriteCond %{SCRIPT_FILENAME} -d [OR] 220 | RewriteCond %{SCRIPT_FILENAME} -f 221 | RewriteRule "(^|/)\." - [F] 222 | ``` 223 | 224 | In alternativa puoi inviare il messaggio "Not Found" error, giving the attacker dude no clue: 225 | ``` apacheconf 226 | RedirectMatch 404 /\..*$ 227 | ``` 228 | 229 | ### Nega l'accesso a Backup e File Sorgenti 230 | 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. 231 | ``` apacheconf 232 | 233 | ## Apache 2.2 234 | Order allow,deny 235 | Deny from all 236 | Satisfy All 237 | 238 | ## Apache 2.4 239 | # Require all denied 240 | 241 | ``` 242 | [Sorgente](https://github.com/h5bp/server-configs-apache) 243 | 244 | ### Disabilita Esplorazione Cartella 245 | ``` apacheconf 246 | Options All -Indexes 247 | ``` 248 | 249 | ### Disabilita Hotlinking delle Immagini 250 | ``` apacheconf 251 | RewriteEngine on 252 | # Rimuovere la riga che segue se vuoi bloccare anche i referrer vuoti 253 | RewriteCond %{HTTP_REFERER} !^$ 254 | 255 | RewriteCond %{HTTP_REFERER} !^https?://(.+\.)?esempio.com [NC] 256 | RewriteRule \.(jpe?g|png|gif|bmp)$ - [NC,F,L] 257 | 258 | # Se vuoi mostrare un banner di "blocco" al posto dell'immagine collegata (hotlinked), 259 | # sostituisci la regola precedente con: 260 | # RewriteRule \.(jpe?g|png|gif|bmp) http://esempio.com/blocked.png [R,L] 261 | ``` 262 | 263 | ### Disabilita Hotlinking delle Immagini per Domini Specifici 264 | A volte vuoi disabilitare il collegamento ad immagini del tuo sito (hotlinking) solo da alcuni cattivoni. 265 | ``` apacheconf 266 | RewriteEngine on 267 | RewriteCond %{HTTP_REFERER} ^https?://(.+\.)?badsite\.com [NC,OR] 268 | RewriteCond %{HTTP_REFERER} ^https?://(.+\.)?badsite2\.com [NC,OR] 269 | RewriteRule \.(jpe?g|png|gif|bmp)$ - [NC,F,L] 270 | 271 | # Se vuoi mostrare un banner di "blocco" al posto dell'immagine collegata (hotlinked), 272 | # sostituisci la regola precedente con: 273 | # RewriteRule \.(jpe?g|png|gif|bmp) http://esempio.com/blocked.png [R,L] 274 | ``` 275 | 276 | ### Proteggi una Cartella con Password 277 | Prima è necessario creare un file `.htpasswd` da qualche parte nell sistema: 278 | ``` bash 279 | htpasswd -c /home/compagnia/.htpasswd boromir 280 | ``` 281 | 282 | E adesso potete utilizzarlo per l'autenticazione: 283 | ``` apacheconf 284 | AuthType Basic 285 | AuthName "Non si entra con facilità" 286 | AuthUserFile /home/compagnia/.htpasswd 287 | Require valid-user 288 | ``` 289 | 290 | ### Proteggi uno o più file con Password 291 | ``` apacheconf 292 | AuthName "Ancora non si entra con facilità" 293 | AuthType Basic 294 | AuthUserFile /home/compagnia/.htpasswd 295 | 296 | 297 | Require valid-user 298 | 299 | 300 | 301 | Require valid-user 302 | 303 | ``` 304 | 305 | ### Blocca i visitatori in base al Referrer 306 | Nega l'accesso a tutti gli utenti che arrivano da (con referrer da) un dominio specifico. 307 | [Sorgente](http://www.htaccess-guide.com/deny-visitors-by-referrer/) 308 | ``` apacheconf 309 | RewriteEngine on 310 | # Options +FollowSymlinks 311 | RewriteCond %{HTTP_REFERER} undominio\.com [NC,OR] 312 | RewriteCond %{HTTP_REFERER} unaltrodominio\.com 313 | RewriteRule .* - [F] 314 | ``` 315 | 316 | ### Previeni l'inclusione del Sito tramite frame (framing) 317 | Previene la possibilità di inserimento del sito web tramite frame (es. inserito all'interno del tag `iframe`) permettendo solo un URI specifico. 318 | ``` apacheconf 319 | SetEnvIf Request_URI "/starry-night" allow_framing=true 320 | Header set X-Frame-Options SAMEORIGIN env=!allow_framing 321 | ``` 322 | 323 | ## Prestazioni 324 | ### Comprimi i File di Testo 325 | ``` apacheconf 326 | 327 | 328 | # Forza la compressione per header manipolati (es. da proxy). 329 | # https://developer.yahoo.com/blogs/ydn/pushing-beyond-gzipping-25601.html 330 | 331 | 332 | SetEnvIfNoCase ^(Accept-EncodXng|X-cept-Encoding|X{15}|~{15}|-{15})$ ^((gzip|deflate)\s*,?\s*)+|[X~-]{4,13}$ HAVE_Accept-Encoding 333 | RequestHeader append Accept-Encoding "gzip,deflate" env=HAVE_Accept-Encoding 334 | 335 | 336 | 337 | # Comprimi tutto l'output segnato con uno dei seguentiMIME-type 338 | # (per le versioni di Apache inferiori a 2.3.7 non è necessario abilitare `mod_filter` 339 | # ed è possibile rimuovere `` e `` lines 340 | # in quanto `AddOutputFilterByType` è ancora nelle direttive principali). 341 | 342 | AddOutputFilterByType DEFLATE application/atom+xml \ 343 | application/javascript \ 344 | application/json \ 345 | application/rss+xml \ 346 | application/vnd.ms-fontobject \ 347 | application/x-font-ttf \ 348 | application/x-web-app-manifest+json \ 349 | application/xhtml+xml \ 350 | application/xml \ 351 | font/opentype \ 352 | image/svg+xml \ 353 | image/x-icon \ 354 | text/css \ 355 | text/html \ 356 | text/plain \ 357 | text/x-component \ 358 | text/xml 359 | 360 | 361 | 362 | ``` 363 | [Sorgente](https://github.com/h5bp/server-configs-apache) 364 | 365 | 366 | ### Imposta gli Header "Expires" 367 | _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. 368 | 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) 369 | ``` apacheconf 370 | 371 | ExpiresActive on 372 | ExpiresDefault "access plus 1 month" 373 | 374 | # CSS 375 | ExpiresByType text/css "access plus 1 year" 376 | 377 | # Interscambio Dati 378 | ExpiresByType application/json "access plus 0 seconds" 379 | ExpiresByType application/xml "access plus 0 seconds" 380 | ExpiresByType text/xml "access plus 0 seconds" 381 | 382 | # Favicon (non può essere rinominato!) 383 | ExpiresByType image/x-icon "access plus 1 week" 384 | 385 | # componenti HTML (HTC) 386 | ExpiresByType text/x-component "access plus 1 month" 387 | 388 | # HTML 389 | ExpiresByType text/html "access plus 0 seconds" 390 | 391 | # JavaScript 392 | ExpiresByType application/javascript "access plus 1 year" 393 | 394 | # File Manifesto 395 | ExpiresByType application/x-web-app-manifest+json "access plus 0 seconds" 396 | ExpiresByType text/cache-manifest "access plus 0 seconds" 397 | 398 | # Media 399 | ExpiresByType audio/ogg "access plus 1 month" 400 | ExpiresByType image/gif "access plus 1 month" 401 | ExpiresByType image/jpeg "access plus 1 month" 402 | ExpiresByType image/png "access plus 1 month" 403 | ExpiresByType video/mp4 "access plus 1 month" 404 | ExpiresByType video/ogg "access plus 1 month" 405 | ExpiresByType video/webm "access plus 1 month" 406 | 407 | # Feed Web 408 | ExpiresByType application/atom+xml "access plus 1 hour" 409 | ExpiresByType application/rss+xml "access plus 1 hour" 410 | 411 | # Web font 412 | ExpiresByType application/font-woff2 "access plus 1 month" 413 | ExpiresByType application/font-woff "access plus 1 month" 414 | ExpiresByType application/vnd.ms-fontobject "access plus 1 month" 415 | ExpiresByType application/x-font-ttf "access plus 1 month" 416 | ExpiresByType font/opentype "access plus 1 month" 417 | ExpiresByType image/svg+xml "access plus 1 month" 418 | 419 | ``` 420 | 421 | ### Disabilita eTags 422 | 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) 423 | ``` apacheconf 424 | 425 | Header unset ETag 426 | 427 | FileETag None 428 | ``` 429 | 430 | ## Miscellanea 431 | 432 | ### Set PHP Variables 433 | ``` apacheconf 434 | php_value 435 | 436 | # Peresempio: 437 | php_value upload_max_filesize 50M 438 | php_value max_execution_time 240 439 | ``` 440 | 441 | ### Pagine Personalizzate di Errore 442 | ``` apacheconf 443 | ErrorDocument 500 "Houston, abbiamo un problema." 444 | ErrorDocument 401 http://errore.esempio.com/mordor.html 445 | ErrorDocument 404 /errori/halflife3.html 446 | ``` 447 | 448 | ### Forza Download 449 | A volte volete poter forzare il browser a scaricare una tipologia di contenuto al posto di mostrarlo. 450 | ``` apacheconf 451 | 452 | ForceType application/octet-stream 453 | Header set Content-Disposition attachment 454 | 455 | ``` 456 | 457 | Adesso c'è lo yang a questo yin: 458 | 459 | ### Previeni il Download 460 | A volte si vuole forzare il brower a mostrare una tipologia di contenuto al posto di farlo scaricare. 461 | ``` apacheconf 462 | 463 | Header set Content-Type text/plain 464 | 465 | ``` 466 | 467 | ### Permetti i Web Font da domini differenti 468 | 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. 469 | ``` apacheconf 470 | 471 | 472 | Header set Access-Control-Allow-Origin "*" 473 | 474 | 475 | ``` 476 | [Sorgente](https://github.com/h5bp/server-configs-apache/issues/32) 477 | 478 | ### Codifica automaticamente in UTF-8 479 | Il contenuto del tuo testo de evessere sempre codificato UTF-8 no? 480 | ``` apacheconf 481 | # Utilizza la codifica UTF-8 per qualasiasi contenuto inviato come text/plain or text/html 482 | AddDefaultCharset utf-8 483 | 484 | # Forza UTF-8 per un numero di formati file 485 | AddCharset utf-8 .atom .css .js .json .rss .vtt .xml 486 | ``` 487 | [Sorgente](https://github.com/h5bp/server-configs-apache) 488 | 489 | ### Passa a un'altra versione di PHP Version 490 | 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. 491 | 492 | ``` apacheconf 493 | AddHandler application/x-httpd-php55 .php 494 | 495 | # Alternatively, you can use AddType 496 | AddType application/x-httpd-php55 .php 497 | ``` 498 | 499 | ### Disabilita Visualizzazione Compatibilità di Internet Explorer 500 | 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à. 501 | 502 | ``` apacheconf 503 | 504 | BrowserMatch MSIE is-msie 505 | Header set X-UA-Compatible IE=edge env=is-msie 506 | 507 | ``` 508 | 509 | ### Rendere disponibili immagini in formato WebP 510 | 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. 511 | 512 | ``` apacheconf 513 | RewriteEngine On 514 | RewriteCond %{HTTP_ACCEPT} image/webp 515 | RewriteCond %{DOCUMENT_ROOT}/$1.webp -f 516 | RewriteRule (.+)\.(jpe?g|png)$ $1.webp [T=image/webp,E=accept:1] 517 | ``` 518 | [Sorgente](https://github.com/vincentorback/WebP-images-with-htaccess) 519 | -------------------------------------------------------------------------------- /Translations/Japanese/README.md: -------------------------------------------------------------------------------- 1 | # .htaccess Snippets 2 | `.htaccess`の便利なスニペットのまとめ 3 | 4 | **免責事項**: スニペットを`.htaccess`で利用した場合、たいていは十分機能するはずですが、一定の修正が必要になることもあります。ご自身の責任で使用してください。 5 | 6 | **重要**: Apache2.4ではいくつかの破壊的変更点があり、それはアクセスコントロールの設定において顕著です。より詳しい情報を知りたい場合は次のリンクをチェックしてください。 [upgrading document](https://httpd.apache.org/docs/2.4/upgrading.html) こちらもどうぞ。 [this issue](https://github.com/phanan/htaccess/issues/2). 7 | 8 | ## クレジット 9 | まとめている、便利なスニペットの大部分はインターネットを通じて収集されたものです。(例えば、かなりの部分は、[Apache Server Configs](https://github.com/h5bp/server-configs-apache)からのものです)。Source等などを正確にクレジットしようと努めていますが、不足してることも考えられます。もしも、ご自分の制作物などがクレジットされるべきだという方がいれば私たちに知らせてください。 10 | 11 | ## 目次 12 | - [URL書き換え&リダイレクト](#rewrite-and-redirection) 13 | - [wwwありに統一](#force-www) 14 | - [wwwありに統一(包括的に)](#force-www-in-a-generic-way) 15 | - [wwwなしに統一](#force-non-www) 16 | - [wwwなしに統一(包括的に)](#force-non-www-in-a-generic-way) 17 | - [httpsに統一](#force-https) 18 | - [httpsに統一する(リバースプロキシー経由)](#force-https-behind-a-proxy) 19 | - [URL末尾をスラッシュ(/)で統一する](#force-trailing-slash) 20 | - [末尾のスラッシュ(/)を取り除く](#remove-trailing-slash) 21 | - [決められたページにリダイレクトさせる](#redirect-a-single-page) 22 | - [ディレクトリエイリアス設定](#alias-a-single-directory) 23 | - [スクリプトへのエイリアスパス](#alias-paths-to-script) 24 | - [とにかくリダイレクトする](#redirect-an-entire-site) 25 | - [クリーンURLエイリアス](#alias-clean-urls) 26 | - [セキュリティ](#security) 27 | - [全アクセス拒否](#deny-all-access) 28 | - [特定のIPを除いたアクセスの拒否](#deny-all-access-except-yours) 29 | - [特定のIPのみアクセスを拒否](#allow-all-access-except-spammers) 30 | - [隠しファイル、隠しディレクトリへのアクセス拒否](#deny-access-to-hidden-files-and-directories) 31 | - [バックアップファイルやソースファイルにアクセスするのを防ぐ](#deny-access-to-backup-and-source-files) 32 | - [ディレクトリ下のファイル一覧の表示禁止](#disable-directory-browsing) 33 | - [画像直リンクの禁止](#disable-image-hotlinking) 34 | - [特定のドメインからの画像直リンクの禁止](#disable-image-hotlinking-for-specific-domains) 35 | - [ディレクトリをパスワードで保護する](#password-protect-a-directory) 36 | - [一つか複数かのファイルをパスワードで保護する](#password-protect-a-file-or-several-files) 37 | - [特定の他所のサイトからアクセスをブロック](#block-visitors-by-referrer) 38 | - [フレーミングされるのを防ぐ](#prevent-framing-the-site) 39 | - [パフォーマンス](#performance) 40 | - [テキストファイルの圧縮](#compress-text-files) 41 | - [Expires(有効期限)ヘッダを設定する](#set-expires-headers) 42 | - [Etagをオフにする](#turn-etags-off) 43 | - [その他の項目](#miscellaneous) 44 | - [PHPの環境変数をセットする](#set-php-variables) 45 | - [カスタムのエラーページ](#custom-error-pages) 46 | - [強制ダウンロード](#force-downloading) 47 | - [ダウンロードを防ぐ](#prevent-downloading) 48 | - [WEBフォントに対する他のドメインからのアクセスを許可する](#allow-cross-domain-fonts) 49 | - [自動的にUTF8エンコードにする](#auto-utf-8-encode) 50 | - [別のPHPのバージョンに切り替える](#switch-to-another-php-version) 51 | - [インターネットエクスプローラーの互換表示をさせない](#disable-internet-explorer-compatibility-view) 52 | - [WebP画像の配信](#serve-webp-images) 53 | 54 | ## URL書き換え&リダイレクト 55 | 注: `mod_rewrite`がインストールされていて有効になってることを前提とします。 56 | 57 | ### wwwありに統一 58 | ``` apacheconf 59 | RewriteEngine on 60 | RewriteCond %{HTTP_HOST} ^example\.com [NC] 61 | RewriteRule ^(.*)$ http://www.example.com/$1 [L,R=301,NC] 62 | ``` 63 | 64 | ### wwwありに統一(包括的に) 65 | ``` apacheconf 66 | RewriteCond %{HTTP_HOST} !^$ 67 | RewriteCond %{HTTP_HOST} !^www\. [NC] 68 | RewriteCond %{HTTPS}s ^on(s)| 69 | RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L] 70 | ``` 71 | 上記の設定はどんなドメインでも動作します。 [Source](https://stackoverflow.com/questions/4916222/htaccess-how-to-force-www-in-a-generic-way) 72 | 73 | 74 | ### wwwなしに統一 75 | 参考 [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のついたドメインかついてないドメインかは好きなほうにすればよいです。 76 | 77 | ``` apacheconf 78 | RewriteEngine on 79 | RewriteCond %{HTTP_HOST} ^www\.example\.com [NC] 80 | RewriteRule ^(.*)$ http://example.com/$1 [L,R=301] 81 | ``` 82 | 83 | ### wwwなしに統一(包括的に) 84 | ``` apacheconf 85 | RewriteEngine on 86 | RewriteCond %{HTTP_HOST} ^www\. 87 | RewriteCond %{HTTPS}s ^on(s)|off 88 | RewriteCond http%1://%{HTTP_HOST} ^(https?://)(www\.)?(.+)$ 89 | RewriteRule ^ %1%3%{REQUEST_URI} [R=301,L] 90 | ``` 91 | 92 | ### httpsに統一 93 | ``` apacheconf 94 | RewriteEngine on 95 | RewriteCond %{HTTPS} !on 96 | RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} 97 | 98 | # Note: It's also recommended to enable HTTP Strict Transport Security (HSTS) 99 | # on your HTTPS website to help prevent man-in-the-middle attacks. 100 | # See https://developer.mozilla.org/en-US/docs/Web/Security/HTTP_strict_transport_security 101 | 102 | Header always set Strict-Transport-Security "max-age=31536000; includeSubDomains" 103 | 104 | ``` 105 | 106 | ### httpsに統一する(リバースプロキシー経由) 107 | リバースプロキシーを経由してhttpsじゃなくなってるいる場合に便利です。 108 | 109 | 110 | ``` apacheconf 111 | RewriteCond %{HTTP:X-Forwarded-Proto} !https 112 | RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} 113 | ``` 114 | 115 | ### URL末尾をスラッシュ(/)で統一する 116 | ``` apacheconf 117 | RewriteCond %{REQUEST_URI} /+[^\.]+$ 118 | RewriteRule ^(.+[^/])$ %{REQUEST_URI}/ [R=301,L] 119 | ``` 120 | 121 | ### 末尾のスラッシュ(/)を取り除く 122 | ``` apacheconf 123 | RewriteCond %{REQUEST_FILENAME} !-d 124 | RewriteRule ^(.*)/$ /$1 [R=301,L] 125 | ``` 126 | ### 決められたページにリダイレクトさせる 127 | ``` apacheconf 128 | Redirect 301 /oldpage.html http://www.example.com/newpage.html 129 | Redirect 301 /oldpage2.html http://www.example.com/folder/ 130 | ``` 131 | [Source](http://css-tricks.com/snippets/htaccess/301-redirects/) 132 | 133 | ### ディレクトリエイリアス設定 134 | ``` apacheconf 135 | RewriteEngine On 136 | RewriteRule ^source-directory/(.*) target-directory/$1 137 | ``` 138 | 139 | ### スクリプトへのエイリアスパス 140 | ``` apacheconf 141 | FallbackResource /index.fcgi 142 | ``` 143 | 144 | 存在しないディレクトリまたはファイルへのリクエストがあれば、スクリプト `index.fcgi` へ転送させるような時に使います。`baz.foo/css/style.css`のような実際にファイルがある時はそちらにアクセスさせておいて、`baz.foo/some/cool/path`のようなクールなURL表現で、`baz.foo/index.fcgi` (`baz.foo`へのリクエストでも同じく扱える)へリクエストを転送させるさせるような時に便利です。あなたのスクリプト環境にさらされるように、PATH_INFO環境変数から元のパスへのアクセスを取得します。 145 | 146 | ``` apacheconf 147 | RewriteEngine On 148 | RewriteRule ^$ index.fcgi/ [QSA,L] 149 | RewriteCond %{REQUEST_FILENAME} !-f 150 | RewriteCond %{REQUEST_FILENAME} !-d 151 | RewriteRule ^(.*)$ index.fcgi/$1 [QSA,L] 152 | ``` 153 | 上記の設定はFallbackResourceより非効率ですが(mod_rewriteは`FallbackResource`を扱うより複雑なため)、より柔軟な設定が可能です。 154 | 155 | ### とにかくリダイレクトする 156 | ``` apacheconf 157 | Redirect 301 / http://newsite.com/ 158 | ``` 159 | この方法はそっくりそのまま別のサイトにリダイレクトさせます。`www.oldsite.com/some/crazy/link.html`にアクセスした場合、`www.newsite.com/some/crazy/link.html`にリダイレクトさせます。新しいドメインに引っ越したときなど、非常に役に立ちます。 [Source](http://css-tricks.com/snippets/htaccess/301-redirects/) 160 | 161 | 162 | ### クリーンURLエイリアス 163 | このスニペットは、クリーンURL用です。拡張子がPHPで、`example.com/users.php`というURLをではなく`example.com/users`というURLとしてあつかえます。 164 | ``` apacheconf 165 | RewriteEngine On 166 | RewriteCond %{SCRIPT_FILENAME} !-d 167 | RewriteRule ^([^.]+)$ $1.php [NC,L] 168 | ``` 169 | [Source](http://www.abeautifulsite.net/access-pages-without-the-php-extension-using-htaccess/) 170 | 171 | ## セキュリティ 172 | ### 全アクセス拒否 173 | ``` apacheconf 174 | ## Apache 2.2 175 | Deny from all 176 | 177 | ## Apache 2.4 178 | # Require all denied 179 | ``` 180 | 181 | あなたも同様にコンテンツをみれなくなるのでよく考えて利用してください。 182 | 183 | ### 特定のIPを除いたアクセスの拒否 184 | ``` apacheconf 185 | ## Apache 2.2 186 | Order deny,allow 187 | Deny from all 188 | Allow from xxx.xxx.xxx.xxx 189 | 190 | ## Apache 2.4 191 | # Require all denied 192 | # Require ip xxx.xxx.xxx.xxx 193 | ``` 194 | `xxx.xxx.xxx.xxx`はあなたのIPです。あなたが例えば12桁のIPのうち最後の3桁を0/12で交換する場合、同じネットワーク内のIPの範囲を指定することになり、別途許可IPを全てリストアップしなければいけないような面倒を回避します。 195 | [Source](http://speckyboy.com/2013/01/08/useful-htaccess-snippets-and-hacks/) 196 | 197 | もちろん逆のバージョンもあります。 198 | 199 | ### 特定のIPのみアクセスを拒否 200 | ``` apacheconf 201 | ## Apache 2.2 202 | Order deny,allow 203 | Allow from all 204 | Deny from xxx.xxx.xxx.xxx 205 | Deny from xxx.xxx.xxx.xxy 206 | 207 | ## Apache 2.4 208 | # Require all granted 209 | # Require not ip xxx.xxx.xxx.xxx 210 | # Require not ip xxx.xxx.xxx.xxy 211 | ``` 212 | 213 | ### 隠しファイル、隠しディレクトリへのアクセス拒否 214 | ドット`.`ではじまる隠しファイルや隠しディレクトリはいかなる時も安全である(閲覧されないようにする)必要があります。例えば、`.htaccess`, `.htpasswd`, `.git`, `.hg` 等です。 215 | ``` apacheconf 216 | RewriteCond %{SCRIPT_FILENAME} -d [OR] 217 | RewriteCond %{SCRIPT_FILENAME} -f 218 | RewriteRule "(^|/)\." - [F] 219 | ``` 220 | 221 | 攻撃者に手がかりを与える代わりに、404エラーページを表示させることができます。 222 | 223 | ``` apacheconf 224 | RedirectMatch 404 /\..*$ 225 | ``` 226 | 227 | ### バックアップファイルやソースファイルにアクセスするのを防ぐ 228 | これらのファイルはviやvimによって置かれたり、公にさらされると、セキュリティ上の危険をもたらすファイルである可能性があります。 229 | ``` apacheconf 230 | 231 | ## Apache 2.2 232 | Order allow,deny 233 | Deny from all 234 | Satisfy All 235 | 236 | ## Apache 2.4 237 | # Require all denied 238 | 239 | ``` 240 | [Source](https://github.com/h5bp/server-configs-apache) 241 | 242 | ### ディレクトリ下のファイル一覧の表示禁止 243 | ``` apacheconf 244 | Options All -Indexes 245 | ``` 246 | 247 | ### 画像直リンクの禁止 248 | ``` apacheconf 249 | RewriteEngine on 250 | # Remove the following line if you want to block blank referrer too 251 | RewriteCond %{HTTP_REFERER} !^$ 252 | 253 | RewriteCond %{HTTP_REFERER} !^https?://(.+\.)?example.com [NC] 254 | RewriteRule \.(jpe?g|png|gif|bmp)$ - [NC,F,L] 255 | 256 | # もしも、直リンクされた画像の代わりにブロックしたことを示す画像を表示させたいのであれば 257 | # `RewriteRule`を次のようにしてください: 258 | # RewriteRule \.(jpe?g|png|gif|bmp) http://example.com/blocked.png [R,L] 259 | ``` 260 | 261 | ### 特定のドメインからの画像直リンクの禁止 262 | 特定のサイトからの画像直リンクを無効にしたい場合です。 263 | ``` apacheconf 264 | RewriteEngine on 265 | RewriteCond %{HTTP_REFERER} ^https?://(.+\.)?badsite\.com [NC,OR] 266 | RewriteCond %{HTTP_REFERER} ^https?://(.+\.)?badsite2\.com [NC,OR] 267 | RewriteRule \.(jpe?g|png|gif|bmp)$ - [NC,F,L] 268 | 269 | # もしも、直リンクされた画像の代わりにブロック下ことを示す画像を表示させたいのであれば 270 | # `RewriteRule`を次のようにしてください: 271 | # RewriteRule \.(jpe?g|png|gif|bmp) http://example.com/blocked.png [R,L] 272 | ``` 273 | 274 | ### ディレクトリをパスワードで保護する 275 | 最初に`.htpasswd`作成してシステムのどこかに配置しておく必要があります。 276 | ``` bash 277 | htpasswd -c /home/fellowship/.htpasswd boromir 278 | ``` 279 | 280 | そして、作成した`.htpasswd`を認証のために使うことができます。 281 | ``` apacheconf 282 | AuthType Basic 283 | AuthName "One does not simply" 284 | AuthUserFile /home/fellowship/.htpasswd 285 | Require valid-user 286 | ``` 287 | 288 | ### 一つか複数かのファイルをパスワードで保護する 289 | ``` apacheconf 290 | AuthName "One still does not simply" 291 | AuthType Basic 292 | AuthUserFile /home/fellowship/.htpasswd 293 | 294 | 295 | Require valid-user 296 | 297 | 298 | 299 | Require valid-user 300 | 301 | ``` 302 | 303 | ### 特定の他所のサイトからアクセスをブロック 304 | この設定は特定のドメインからのアクセスをブロックします 305 | [Source](http://www.htaccess-guide.com/deny-visitors-by-referrer/) 306 | ``` apacheconf 307 | RewriteEngine on 308 | # Options +FollowSymlinks 309 | RewriteCond %{HTTP_REFERER} somedomain\.com [NC,OR] 310 | RewriteCond %{HTTP_REFERER} anotherdomain\.com 311 | RewriteRule .* - [F] 312 | ``` 313 | 314 | ### フレーミングされるのを防ぐ 315 | 下記の設定はウェブサイトがフレーム内に表示(IEでは`iframe`を使う)されるのを防止しています。同時に特定のURIの時には許可しています。 316 | ``` apacheconf 317 | SetEnvIf Request_URI "/starry-night" allow_framing=true 318 | Header set X-Frame-Options SAMEORIGIN env=!allow_framing 319 | ``` 320 | 321 | ## パフォーマンス 322 | ### テキストファイルの圧縮 323 | ``` apacheconf 324 | 325 | 326 | # Force compression for mangled headers. 327 | # https://developer.yahoo.com/blogs/ydn/pushing-beyond-gzipping-25601.html 328 | 329 | 330 | SetEnvIfNoCase ^(Accept-EncodXng|X-cept-Encoding|X{15}|~{15}|-{15})$ ^((gzip|deflate)\s*,?\s*)+|[X~-]{4,13}$ HAVE_Accept-Encoding 331 | RequestHeader append Accept-Encoding "gzip,deflate" env=HAVE_Accept-Encoding 332 | 333 | 334 | 335 | # Compress all output labeled with one of the following MIME-types 336 | # (for Apache versions below 2.3.7, you don't need to enable `mod_filter` 337 | # and can remove the `` and `` lines 338 | # as `AddOutputFilterByType` is still in the core directives). 339 | 340 | AddOutputFilterByType DEFLATE application/atom+xml \ 341 | application/javascript \ 342 | application/json \ 343 | application/rss+xml \ 344 | application/vnd.ms-fontobject \ 345 | application/x-font-ttf \ 346 | application/x-web-app-manifest+json \ 347 | application/xhtml+xml \ 348 | application/xml \ 349 | font/opentype \ 350 | image/svg+xml \ 351 | image/x-icon \ 352 | text/css \ 353 | text/html \ 354 | text/plain \ 355 | text/x-component \ 356 | text/xml 357 | 358 | 359 | 360 | ``` 361 | [Source](https://github.com/h5bp/server-configs-apache) 362 | 363 | 364 | ### Expires(有効期限)ヘッダを設定する 365 | ブラウザはexpires (有効期限)ヘッダをみてコンテンツをサーバーから取得すべきか、キャッシュから取得するかを判断します。静的コンテンツの有効期限はいくらか遠い未来に設定したほうがよいといえます。 366 | ``` apacheconf 367 | 368 | ExpiresActive on 369 | ExpiresDefault "access plus 1 month" 370 | 371 | # CSS 372 | ExpiresByType text/css "access plus 1 year" 373 | 374 | # Data interchange 375 | ExpiresByType application/json "access plus 0 seconds" 376 | ExpiresByType application/xml "access plus 0 seconds" 377 | ExpiresByType text/xml "access plus 0 seconds" 378 | 379 | # Favicon (cannot be renamed!) 380 | ExpiresByType image/x-icon "access plus 1 week" 381 | 382 | # HTML components (HTCs) 383 | ExpiresByType text/x-component "access plus 1 month" 384 | 385 | # HTML 386 | ExpiresByType text/html "access plus 0 seconds" 387 | 388 | # JavaScript 389 | ExpiresByType application/javascript "access plus 1 year" 390 | 391 | # Manifest files 392 | ExpiresByType application/x-web-app-manifest+json "access plus 0 seconds" 393 | ExpiresByType text/cache-manifest "access plus 0 seconds" 394 | 395 | # Media 396 | ExpiresByType audio/ogg "access plus 1 month" 397 | ExpiresByType image/gif "access plus 1 month" 398 | ExpiresByType image/jpeg "access plus 1 month" 399 | ExpiresByType image/png "access plus 1 month" 400 | ExpiresByType video/mp4 "access plus 1 month" 401 | ExpiresByType video/ogg "access plus 1 month" 402 | ExpiresByType video/webm "access plus 1 month" 403 | 404 | # Web feeds 405 | ExpiresByType application/atom+xml "access plus 1 hour" 406 | ExpiresByType application/rss+xml "access plus 1 hour" 407 | 408 | # Web fonts 409 | ExpiresByType application/font-woff2 "access plus 1 month" 410 | ExpiresByType application/font-woff "access plus 1 month" 411 | ExpiresByType application/vnd.ms-fontobject "access plus 1 month" 412 | ExpiresByType application/x-font-ttf "access plus 1 month" 413 | ExpiresByType font/opentype "access plus 1 month" 414 | ExpiresByType image/svg+xml "access plus 1 month" 415 | 416 | ``` 417 | 418 | ### Etagをオフにする 419 | `ETag`ヘッダを取り除くことによって、ブラウザ側が持っているキャッシュファイルと、サーバー側にある実ファイルの内容、更新日などが同じかどうか等の検証作業を無効にして、`Cache-Control` と `Expires` ヘッダを利用するようにします。 420 | ``` apacheconf 421 | 422 | Header unset ETag 423 | 424 | FileETag None 425 | ``` 426 | 427 | ## その他の項目 428 | 429 | ### PHPの環境変数をセットする 430 | ``` apacheconf 431 | php_value 432 | 433 | # 例: 434 | php_value upload_max_filesize 50M 435 | php_value max_execution_time 240 436 | ``` 437 | 438 | ### カスタムのエラーページ 439 | ``` apacheconf 440 | ErrorDocument 500 "Houston, we have a problem." 441 | ErrorDocument 401 http://error.example.com/mordor.html 442 | ErrorDocument 404 /errors/halflife3.html 443 | ``` 444 | 445 | ### 強制ダウンロード 446 | コンテンツをブラウザに表示させるのではなく、強制的にダウンロードさせたい場合は次のようにします。 447 | ``` apacheconf 448 | 449 | ForceType application/octet-stream 450 | Header set Content-Disposition attachment 451 | 452 | ``` 453 | 454 | Now there is a yang to this yin: 455 | 456 | ### ダウンロードを防ぐ 457 | コンテンツをダウンロードさせるのではなく内容をそのままブラウザに表示させたい時は次のようにします。 458 | ``` apacheconf 459 | 460 | Header set Content-Type text/plain 461 | 462 | ``` 463 | 464 | ### WEBフォントに対する他のドメインからのアクセスを許可する 465 | IE, Firefoxのだとクロスドメイン制約のため、WEBフォントが正常に機能しない可能性があります。[CORS](https://en.wikipedia.org/wiki/Cross-origin_resource_sharing) このスニペットはその問題を解決します。 466 | ``` apacheconf 467 | 468 | 469 | Header set Access-Control-Allow-Origin "*" 470 | 471 | 472 | ``` 473 | [Source](https://github.com/h5bp/server-configs-apache/issues/32) 474 | 475 | ### 自動的にUTF8エンコードにする 476 | あなたのテキストコンテンツを常にUTF-8エンコードする時は次の設定をご利用ください。 477 | ``` apacheconf 478 | # text/plain か text/htmlを配信する時はUTF-8を使用します。 479 | AddDefaultCharset utf-8 480 | 481 | # 特定のファイルフォーマットで強制的にUTF-8を使う 482 | AddCharset utf-8 .atom .css .js .json .rss .vtt .xml 483 | ``` 484 | [Source](https://github.com/h5bp/server-configs-apache) 485 | 486 | ### 別のPHPのバージョンに切り替える 487 | もしも、あなたが共有のホストを利用している場合、おそらく複数のバージョンのPHPがインストールされている可能性があり、時には自分のウェブサイトで特定のバージョンのPHPを使いたくなるかもしれません。例えば、ララベルではPHP5.4以上である必要があります。次のスニペットを使えば自分のウェブサイト用のPHPバージョンに切り替える事ができます。 488 | 489 | ``` apacheconf 490 | AddHandler application/x-httpd-php55 .php 491 | 492 | # 代わりにAddTypeを使うこともできます。 493 | AddType application/x-httpd-php55 .php 494 | ``` 495 | 496 | ### インターネットエクスプローラーの互換表示をさせない 497 | IEの互換表示モードはIEにおけるウェブサイトの表示に影響があたえることがあります。次のスニペットを使用することで、IEに最新のエンジンでページをレンダリングさせて、互換表示をさせなくすることができます。 498 | 499 | ``` apacheconf 500 | 501 | BrowserMatch MSIE is-msie 502 | Header set X-UA-Compatible IE=edge env=is-msie 503 | 504 | ``` 505 | 506 | ### WebP画像の配信 507 | もしも、[WebP images](https://developers.google.com/speed/webp/?csw=1) がサポートされていて、同じでディレクトリ下に、同じ名前のファイル名で、.webp と jpg/pngの拡張子のファイルがあった場合、WebP画像(.webp)が優先して配信されます。 508 | 509 | ``` apacheconf 510 | RewriteEngine On 511 | RewriteCond %{HTTP_ACCEPT} image/webp 512 | RewriteCond %{DOCUMENT_ROOT}/$1.webp -f 513 | RewriteRule (.+)\.(jpe?g|png)$ $1.webp [T=image/webp,E=accept:1] 514 | ``` 515 | [Source](https://github.com/vincentorback/WebP-images-with-htaccess) 516 | -------------------------------------------------------------------------------- /Translations/Portuguese-BR/README.md: -------------------------------------------------------------------------------- 1 | # .htaccess Snippets 2 | Uma coleção de snippets .htaccess úteis, tudo em um só lugar. 3 | 4 | **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. 5 | 6 | **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). 7 | 8 | ## Créditos 9 | O que estamos fazendo aqui é principalmente a coleta trechos úteis de todo o interwebs (por exemplo, uma boa parte é de 10 | [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. 11 | 12 | ## Tabela de Conteúdo 13 | - [Rewrite and Redirection](#rewrite-and-redirection) 14 | - [Force www](#force-www) 15 | - [Force www in a Generic Way](#force-www-in-a-generic-way) 16 | - [Force non-www](#force-non-www) 17 | - [Force non-www in a Generic Way](#force-non-www-in-a-generic-way) 18 | - [Force HTTPS](#force-https) 19 | - [Force HTTPS Behind a Proxy](#force-https-behind-a-proxy) 20 | - [Force Trailing Slash](#force-trailing-slash) 21 | - [Remove Trailing Slash](#remove-trailing-slash) 22 | - [Redirect a Single Page](#redirect-a-single-page) 23 | - [Alias a Single Directory](#alias-a-single-directory) 24 | - [Alias Paths to Script](#alias-paths-to-script) 25 | - [Redirect an Entire Site](#redirect-an-entire-site) 26 | - [Alias "Clean" URLs](#alias-clean-urls) 27 | - [Security](#security) 28 | - [Deny All Access](#deny-all-access) 29 | - [Deny All Access Except Yours](#deny-all-access-except-yours) 30 | - [Allow All Access Except Spammers'](#allow-all-access-except-spammers) 31 | - [Deny Access to Hidden Files and Directories](#deny-access-to-hidden-files-and-directories) 32 | - [Deny Access to Backup and Source Files](#deny-access-to-backup-and-source-files) 33 | - [Disable Directory Browsing](#disable-directory-browsing) 34 | - [Disable Image Hotlinking](#disable-image-hotlinking) 35 | - [Disable Image Hotlinking for Specific Domains](#disable-image-hotlinking-for-specific-domains) 36 | - [Password Protect a Directory](#password-protect-a-directory) 37 | - [Password Protect a File or Several Files](#password-protect-a-file-or-several-files) 38 | - [Block Visitors by Referrer](#block-visitors-by-referrer) 39 | - [Prevent Framing the Site](#prevent-framing-the-site) 40 | - [Performance](#performance) 41 | - [Compress Text Files](#compress-text-files) 42 | - [Set Expires Headers](#set-expires-headers) 43 | - [Turn eTags Off](#turn-etags-off) 44 | - [Miscellaneous](#miscellaneous) 45 | - [Set PHP Variables](#set-php-variables) 46 | - [Custom Error Pages](#custom-error-pages) 47 | - [Force Downloading](#force-downloading) 48 | - [Prevent Downloading](#prevent-downloading) 49 | - [Allow Cross-Domain Fonts](#allow-cross-domain-fonts) 50 | - [Auto UTF-8 Encode](#auto-utf-8-encode) 51 | - [Switch to Another PHP Version](#switch-to-another-php-version) 52 | - [Disable Internet Explorer Compatibility View](#disable-internet-explorer-compatibility-view) 53 | - [Serve WebP Images](#serve-webp-images) 54 | 55 | ## Rewrite and Redirection 56 | Nota: Presume-se que você tem `mod_rewrite` instalado e habilitado. 57 | 58 | ### Force www 59 | ``` apacheconf 60 | RewriteEngine on 61 | RewriteCond %{HTTP_HOST} ^example\.com [NC] 62 | RewriteRule ^(.*)$ http://www.example.com/$1 [L,R=301,NC] 63 | ``` 64 | 65 | ### Force www in a Generic Way 66 | ``` apacheconf 67 | RewriteCond %{HTTP_HOST} !^$ 68 | RewriteCond %{HTTP_HOST} !^www\. [NC] 69 | RewriteCond %{HTTPS}s ^on(s)| 70 | RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L] 71 | ``` 72 | Isso funciona para _any_ domain. [Source](https://stackoverflow.com/questions/4916222/htaccess-how-to-force-www-in-a-generic-way) 73 | 74 | ### Force non-www 75 | 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: 76 | ``` apacheconf 77 | RewriteEngine on 78 | RewriteCond %{HTTP_HOST} ^www\.example\.com [NC] 79 | RewriteRule ^(.*)$ http://example.com/$1 [L,R=301] 80 | ``` 81 | 82 | ### Force non-www in a Generic Way 83 | ``` apacheconf 84 | RewriteEngine on 85 | RewriteCond %{HTTP_HOST} ^www\. 86 | RewriteCond %{HTTPS}s ^on(s)|off 87 | RewriteCond http%1://%{HTTP_HOST} ^(https?://)(www\.)?(.+)$ 88 | RewriteRule ^ %1%3%{REQUEST_URI} [R=301,L] 89 | ``` 90 | 91 | ### Force HTTPS 92 | ``` apacheconf 93 | RewriteEngine on 94 | RewriteCond %{HTTPS} !on 95 | RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} 96 | 97 | # Nota: Também é recomendável habilitar HTTP Strict Transport Segurança (HSTS) 98 | # Em seu site HTTPS para ajudar a prevenir ataques man-in-the-middle. 99 | # Veja https://developer.mozilla.org/en-US/docs/Web/Security/HTTP_strict_transport_security 100 | 101 | Header sempre definido Strict-Transport-Security "max-age=31536000; includeSubDomains" 102 | 103 | ``` 104 | 105 | ### Force HTTPS Behind a Proxy 106 | Útil se você tiver um proxy na frente do seu servidor a realização de terminação TLS. 107 | ``` apacheconf 108 | RewriteCond %{HTTP:X-Forwarded-Proto} !https 109 | RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} 110 | ``` 111 | 112 | ### Force Trailing Slash 113 | ``` apacheconf 114 | RewriteCond %{REQUEST_URI} /+[^\.]+$ 115 | RewriteRule ^(.+[^/])$ %{REQUEST_URI}/ [R=301,L] 116 | ``` 117 | 118 | ### Remove Trailing Slash 119 | ``` apacheconf 120 | RewriteCond %{REQUEST_FILENAME} !-d 121 | RewriteRule ^(.*)/$ /$1 [R=301,L] 122 | ``` 123 | ### Redirect a Single Page 124 | ``` apacheconf 125 | Redirect 301 /oldpage.html http://www.example.com/newpage.html 126 | Redirect 301 /oldpage2.html http://www.example.com/folder/ 127 | ``` 128 | [Source](http://css-tricks.com/snippets/htaccess/301-redirects/) 129 | 130 | ### Alias a Single Directory 131 | ``` apacheconf 132 | RewriteEngine On 133 | RewriteRule ^source-directory/(.*) target-directory/$1 134 | ``` 135 | 136 | ### Alias Paths to Script 137 | ``` apacheconf 138 | FallbackResource /index.fcgi 139 | ``` 140 | 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. 141 | 142 | ``` apacheconf 143 | RewriteEngine On 144 | RewriteRule ^$ index.fcgi/ [QSA,L] 145 | RewriteCond %{REQUEST_FILENAME} !-f 146 | RewriteCond %{REQUEST_FILENAME} !-d 147 | RewriteRule ^(.*)$ index.fcgi/$1 [QSA,L] 148 | ``` 149 | 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. 150 | 151 | ### Redirect an Entire Site 152 | ``` apacheconf 153 | Redirect 301 / http://newsite.com/ 154 | ``` 155 | 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/) 156 | 157 | ### Alias "Clean" URLs 158 | 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`. 159 | ``` apacheconf 160 | RewriteEngine On 161 | RewriteCond %{SCRIPT_FILENAME} !-d 162 | RewriteRule ^([^.]+)$ $1.php [NC,L] 163 | ``` 164 | [Source](http://www.abeautifulsite.net/access-pages-without-the-php-extension-using-htaccess/) 165 | 166 | ## Security 167 | ### Deny All Access 168 | ``` apacheconf 169 | ## Apache 2.2 170 | Deny from all 171 | 172 | ## Apache 2.4 173 | # Require all denied 174 | ``` 175 | 176 | Mas espere, isso irá bloqueá-lo a partir do seu conteúdo, bem! Assim, a introdução de ... 177 | 178 | ### Deny All Access Except Yours 179 | ``` apacheconf 180 | ## Apache 2.2 181 | Order deny,allow 182 | Deny from all 183 | Allow from xxx.xxx.xxx.xxx 184 | 185 | ## Apache 2.4 186 | # Require all denied 187 | # Require ip xxx.xxx.xxx.xxx 188 | ``` 189 | `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/) 190 | 191 | Agora é claro que há uma versão invertida: 192 | 193 | ### Allow All Access Except Spammers' 194 | ``` apacheconf 195 | ## Apache 2.2 196 | Order deny,allow 197 | Deny from xxx.xxx.xxx.xxx 198 | Deny from xxx.xxx.xxx.xxy 199 | 200 | ## Apache 2.4 201 | # Require all granted 202 | # Require not ip xxx.xxx.xxx.xxx 203 | # Require not ip xxx.xxx.xxx.xxy 204 | ``` 205 | 206 | ### Deny Access to Hidden Files and Directories 207 | 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`... 208 | ``` apacheconf 209 | RewriteCond %{SCRIPT_FILENAME} -d [OR] 210 | RewriteCond %{SCRIPT_FILENAME} -f 211 | RewriteRule "(^|/)\." - [F] 212 | ``` 213 | 214 | Alternativamente, você pode simplesmente levantar uma `Not Found` erro, dando a cara atacante nenhuma pista: 215 | ``` apacheconf 216 | RedirectMatch 404 /\..*$ 217 | ``` 218 | 219 | ### Deny Access to Backup and Source Files 220 | 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. 221 | ``` apacheconf 222 | 223 | ## Apache 2.2 224 | Order allow,deny 225 | Deny from all 226 | Satisfy All 227 | 228 | ## Apache 2.4 229 | # Require all denied 230 | 231 | ``` 232 | [Source](https://github.com/h5bp/server-configs-apache) 233 | 234 | ### Disable Directory Browsing 235 | ``` apacheconf 236 | Options All -Indexes 237 | ``` 238 | 239 | ### Disable Image Hotlinking 240 | ``` apacheconf 241 | RewriteEngine on 242 | # Remova a seguinte linha se você deseja bloquear referrer em branco também 243 | RewriteCond %{HTTP_REFERER} !^$ 244 | 245 | RewriteCond %{HTTP_REFERER} !^https?://(.+\.)?example.com [NC] 246 | RewriteRule \.(jpe?g|png|gif|bmp)$ - [NC,F,L] 247 | 248 | # Se você deseja exibir um banner "bloqueada" em lugar da imagem hotlink, 249 | # Substituir a regra acima, com: 250 | # RewriteRule \.(jpe?g|png|gif|bmp) http://example.com/blocked.png [R,L] 251 | ``` 252 | 253 | ### Disable Image Hotlinking for Specific Domains 254 | Às vezes você quer desabilitar imagem hotlinking de alguns bandidos só. 255 | ``` apacheconf 256 | RewriteEngine on 257 | RewriteCond %{HTTP_REFERER} ^https?://(.+\.)?badsite\.com [NC,OR] 258 | RewriteCond %{HTTP_REFERER} ^https?://(.+\.)?badsite2\.com [NC,OR] 259 | RewriteRule \.(jpe?g|png|gif|bmp)$ - [NC,F,L] 260 | 261 | # Se você deseja exibir um banner "bloqueada" em lugar da imagem hotlink, 262 | # Substituir a regra acima, com: 263 | # RewriteRule \.(jpe?g|png|gif|bmp) http://example.com/blocked.png [R,L] 264 | ``` 265 | 266 | ### Password Protect a Directory 267 | Primeiro você precisa criar um arquivo `.htpasswd` em algum lugar do sistema: 268 | ``` bash 269 | htpasswd -c /home/fellowship/.htpasswd boromir 270 | ``` 271 | 272 | Em seguida, você pode usá-lo para autenticação: 273 | ``` apacheconf 274 | AuthType Basic 275 | AuthName "One does not simply" 276 | AuthUserFile /home/fellowship/.htpasswd 277 | Require valid-user 278 | ``` 279 | 280 | ### Password Protect a File or Several Files 281 | ``` apacheconf 282 | AuthName "One still does not simply" 283 | AuthType Basic 284 | AuthUserFile /home/fellowship/.htpasswd 285 | 286 | 287 | Require valid-user 288 | 289 | 290 | 291 | Require valid-user 292 | 293 | ``` 294 | 295 | ### Block Visitors by Referrer 296 | Este nega o acesso para todos os usuários que estão vindo de (indicado por) um domínio específico. 297 | [Source](http://www.htaccess-guide.com/deny-visitors-by-referrer/) 298 | ``` apacheconf 299 | RewriteEngine on 300 | # Options +FollowSymlinks 301 | RewriteCond %{HTTP_REFERER} somedomain\.com [NC,OR] 302 | RewriteCond %{HTTP_REFERER} anotherdomain\.com 303 | RewriteRule .* - [F] 304 | ``` 305 | 306 | ### Prevent Framing the Site 307 | 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. 308 | ``` apacheconf 309 | SetEnvIf Request_URI "/starry-night" allow_framing=true 310 | Header set X-Frame-Options SAMEORIGIN env=!allow_framing 311 | ``` 312 | 313 | ## Performance 314 | ### Compress Text Files 315 | ``` apacheconf 316 | 317 | 318 | # Force compression for mangled headers. 319 | # https://developer.yahoo.com/blogs/ydn/pushing-beyond-gzipping-25601.html 320 | 321 | 322 | SetEnvIfNoCase ^(Accept-EncodXng|X-cept-Encoding|X{15}|~{15}|-{15})$ ^((gzip|deflate)\s*,?\s*)+|[X~-]{4,13}$ HAVE_Accept-Encoding 323 | RequestHeader append Accept-Encoding "gzip,deflate" env=HAVE_Accept-Encoding 324 | 325 | 326 | 327 | # Comprimir toda a saída marcada com um dos seguintes procedimentos MIME-types 328 | # (para versões do Apache 2.3.7 abaixo, você não precisa habilitar `mod_filter` 329 | # pode remover as linhas `` e `` 330 | # como `AddOutputFilterByType` ainda está em diretivas principais). 331 | 332 | AddOutputFilterByType DEFLATE application/atom+xml \ 333 | application/javascript \ 334 | application/json \ 335 | application/rss+xml \ 336 | application/vnd.ms-fontobject \ 337 | application/x-font-ttf \ 338 | application/x-web-app-manifest+json \ 339 | application/xhtml+xml \ 340 | application/xml \ 341 | font/opentype \ 342 | image/svg+xml \ 343 | image/x-icon \ 344 | text/css \ 345 | text/html \ 346 | text/plain \ 347 | text/x-component \ 348 | text/xml 349 | 350 | 351 | 352 | ``` 353 | [Source](https://github.com/h5bp/server-configs-apache) 354 | 355 | 356 | ### Set Expires Headers 357 | _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. 358 | 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) 359 | ``` apacheconf 360 | 361 | ExpiresActive on 362 | ExpiresDefault "access plus 1 month" 363 | 364 | # CSS 365 | ExpiresByType text/css "access plus 1 year" 366 | 367 | # Data interchange 368 | ExpiresByType application/json "access plus 0 seconds" 369 | ExpiresByType application/xml "access plus 0 seconds" 370 | ExpiresByType text/xml "access plus 0 seconds" 371 | 372 | # Favicon (cannot be renamed!) 373 | ExpiresByType image/x-icon "access plus 1 week" 374 | 375 | # HTML components (HTCs) 376 | ExpiresByType text/x-component "access plus 1 month" 377 | 378 | # HTML 379 | ExpiresByType text/html "access plus 0 seconds" 380 | 381 | # JavaScript 382 | ExpiresByType application/javascript "access plus 1 year" 383 | 384 | # Manifest files 385 | ExpiresByType application/x-web-app-manifest+json "access plus 0 seconds" 386 | ExpiresByType text/cache-manifest "access plus 0 seconds" 387 | 388 | # Media 389 | ExpiresByType audio/ogg "access plus 1 month" 390 | ExpiresByType image/gif "access plus 1 month" 391 | ExpiresByType image/jpeg "access plus 1 month" 392 | ExpiresByType image/png "access plus 1 month" 393 | ExpiresByType video/mp4 "access plus 1 month" 394 | ExpiresByType video/ogg "access plus 1 month" 395 | ExpiresByType video/webm "access plus 1 month" 396 | 397 | # Web feeds 398 | ExpiresByType application/atom+xml "access plus 1 hour" 399 | ExpiresByType application/rss+xml "access plus 1 hour" 400 | 401 | # Web fonts 402 | ExpiresByType application/font-woff2 "access plus 1 month" 403 | ExpiresByType application/font-woff "access plus 1 month" 404 | ExpiresByType application/vnd.ms-fontobject "access plus 1 month" 405 | ExpiresByType application/x-font-ttf "access plus 1 month" 406 | ExpiresByType font/opentype "access plus 1 month" 407 | ExpiresByType image/svg+xml "access plus 1 month" 408 | 409 | ``` 410 | 411 | ### Turn eTags Off 412 | 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) 413 | ``` apacheconf 414 | 415 | Header unset ETag 416 | 417 | FileETag None 418 | ``` 419 | 420 | ## Miscellaneous 421 | 422 | ### Set PHP Variables 423 | ``` apacheconf 424 | php_value 425 | 426 | # Por exemplo: 427 | php_value upload_max_filesize 50M 428 | php_value max_execution_time 240 429 | ``` 430 | 431 | ### Custom Error Pages 432 | ``` apacheconf 433 | ErrorDocument 500 "Houston, você tem um problema." 434 | ErrorDocument 401 http://error.example.com/mordor.html 435 | ErrorDocument 404 /errors/halflife3.html 436 | ``` 437 | 438 | ### Force Downloading 439 | Às vezes você quer forçar o navegador para baixar algum conteúdo em vez de exibi-lo. 440 | ``` apacheconf 441 | 442 | ForceType application/octet-stream 443 | Header set Content-Disposition attachment 444 | 445 | ``` 446 | 447 | Agora a um yang a este yin: 448 | 449 | ### Prevent Downloading 450 | Às vezes você quer forçar o navegador para exibir algum conteúdo em vez de baixá-lo. 451 | ``` apacheconf 452 | 453 | Header set Content-Type text/plain 454 | 455 | ``` 456 | 457 | ### Allow Cross-Domain Fonts 458 | 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. 459 | ``` apacheconf 460 | 461 | 462 | Header set Access-Control-Allow-Origin "*" 463 | 464 | 465 | ``` 466 | [Source](https://github.com/h5bp/server-configs-apache/issues/32) 467 | 468 | ### Auto UTF-8 Encode 469 | Seu texto deve ser sempre codificação UTF-8, não? 470 | ``` apacheconf 471 | # Use codificação UTF-8 para qualquer coisa como text/plain ou text/html 472 | AddDefaultCharset utf-8 473 | 474 | # Força UTF-8 para um número de formatos de arquivo 475 | AddCharset utf-8 .atom .css .js .json .rss .vtt .xml 476 | ``` 477 | [Source](https://github.com/h5bp/server-configs-apache) 478 | 479 | ### Switch to Another PHP Version 480 | 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ê. 481 | 482 | ``` apacheconf 483 | AddHandler application/x-httpd-php55 .php 484 | 485 | # Alternativamente, você pode usar AddType 486 | AddType application/x-httpd-php55 .php 487 | ``` 488 | 489 | ### Disable Internet Explorer Compatibility View 490 | 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. 491 | 492 | ``` apacheconf 493 | 494 | BrowserMatch MSIE is-msie 495 | Header set X-UA-Compatible IE=edge env=is-msie 496 | 497 | ``` 498 | 499 | ### Serve WebP Images 500 | 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. 501 | 502 | ``` apacheconf 503 | RewriteEngine On 504 | RewriteCond %{HTTP_ACCEPT} image/webp 505 | RewriteCond %{DOCUMENT_ROOT}/$1.webp -f 506 | RewriteRule (.+)\.(jpe?g|png)$ $1.webp [T=image/webp,E=accept:1] 507 | ``` 508 | [Source](https://github.com/vincentorback/WebP-images-with-htaccess) 509 | -------------------------------------------------------------------------------- /Translations/Russian/README.md: -------------------------------------------------------------------------------- 1 | # .htaccess сниппеты [![Awesome](https://cdn.rawgit.com/sindresorhus/awesome/d7305f38d29fed78fa85652e3a63e154dd8e8829/media/badge.svg)](https://github.com/sindresorhus/awesome) 2 | Коллекция .htaccess сниппетов, собранных в одном месте. 3 | 4 | **Дисклеймер**: Перед тем, как использовать сниппет в файле `.htaccess`, в большинстве случаев необходимо сделать небольшие коррекции (поменять название папки или файла, изменить URL и т.д.). Используйте сниппеты на свой страх и риск. 5 | 6 | **ВАЖНО**: В Apache 2.4 появилось несколько важных изменений, особенно в конфигурации управления доступами. Чтобы узнать больше об этих и других изменениях перейдите по этой [ссылке](https://httpd.apache.org/docs/2.4/upgrading.html), а также просмотрите это [ишью](https://github.com/phanan/htaccess/issues/2). 7 | 8 | ## Поддержка 9 | Что мы делаем? Здесь собраны самые полезные сниппеты для файла `.htaccess` из всего интернета (например, много разных приемов из [Apache Server Configs](https://github.com/h5bp/server-configs-apache) мы собрали в одном месте). Не исключено, что мы могли что-то упустить. Если вы заметили где-то ошибки или несоответствия, пожалуйста, сообщите нам об этом или сделайте Pull Request. 10 | Подробнее о том, как помочь проекту и делать Pull Request'ы, вы можете прочитать в [этой статье](https://habrahabr.ru/post/275219/) на Хабрахабр. 11 | 12 | ## Содержание 13 | - [Rewrite и Redirect](#rewrite-и-redirect) 14 | - [Перенаправление с без www на с www](#Перенаправление-с-без-www-на-с-www) 15 | - [Перенаправление с без www на с www для HTTP или HTTPS](#Перенаправление-с-без-www-на-с-www-для-http-или-https) 16 | - [Перенаправление с www на без www](#Перенаправление-с-www-на-без-www) 17 | - [Перенаправление с www на без www для HTTP или HTTPS](#Перенаправление-с-www-на-без-www-для-http-или-https) 18 | - [Принудительное использование HTTPS](#Принудительное-использование-https) 19 | - [Принудительное использование HTTPS за прокси](#Принудительное-использование-https-за-прокси) 20 | - [Вставить завершающий слэш](#Вставить-завершающий-слэш) 21 | - [Удалить завершающий слэш](#Удалить-завершающий-слэш) 22 | - [Редирект со страницы на страницу](#Редирект-со-страницы-на-страницу) 23 | - [Редирект с использованием RedirectMatch](#Редирект-с-использованием-redirectmatch) 24 | - [Алиас для определенной директории](#Алиас-для-определенной-директории) 25 | - [Алиас пути до скрипта](#Алиас-пути-до-скрипта) 26 | - [Редирект всего сайта](#Редирект-всего-сайта) 27 | - [Использовать чистые URL](#Использовать-чистые-url) 28 | - [Безопасность](#Безопасность) 29 | - [Запретить доступ всем](#Запретить-доступ-всем) 30 | - [Запретить доступ всем, кроме...](#Запретить-доступ-всем-кроме) 31 | - [Разрешить доступ всем, кроме...](#Разрешить-доступ-всем-кроме) 32 | - [Запретить доступ к скрытым файлам и директориям](#Запретить-доступ-к-скрытым-файлам-и-директориям) 33 | - [Запретить доступ к файлам](#Запретить-доступ-к-файлам) 34 | - [Запретить листинг директорий](#Запретить-листинг-директорий) 35 | - [Запретить хотлинкинг изображений](#Запретить-хотлинкинг-изображений) 36 | - [Запретить хотлинкинг изображений для определенных доменов](#Запретить-хотлинкинг-изображений-для-определенных-доменов) 37 | - [Защитить паролем директорию](#Защитить-паролем-директорию) 38 | - [Защитить паролем один или несколько файлов](#Защитить-паролем-один-или-несколько-файлов) 39 | - [Заблокировать посетителя по Referrer](#Заблокировать-посетителя-по-referrer) 40 | - [Запретить рендеринг сайта во фрейме](#Запретить-рендеринг-сайта-во-фрейме) 41 | - [Производительность](#Производительность) 42 | - [Сжатие текстовых файлов](#Сжатие-текстовых-файлов) 43 | - [Установить Expires Headers](#Установить-expires-headers) 44 | - [Выключить eTags](#Выключить-etags) 45 | - [Разное](#Разное) 46 | - [Настройка PHP](#Настройка-php) 47 | - [Пользовательские страницы ошибок](#Пользовательские-страницы-ошибок) 48 | - [Принудительная загрузка (скачивать файл вместо отображения в браузере)](#Принудительная-загрузка-скачивать-файл-вместо-отображения-в-браузере) 49 | - [Запретить загрузку (отображать plain в браузере)](#Запретить-загрузку-отображать-plain-в-браузере) 50 | - [Разрешить кроссдоменные шрифты](#Разрешить-кроссдоменные-шрифты) 51 | - [Установить по умолчанию кодировку UTF-8](#Установить-по-умолчанию-кодировку-utf-8) 52 | - [Переключиться на другую версию PHP](#Переключиться-на-другую-версию-php) 53 | - [Выключить режим совместимости в Internet Explorer](#Выключить-режим-совместимости-в-internet-explorer) 54 | - [Обработка WebP изображений](#Обработка-webp-изображений) 55 | 56 | ## Rewrite и Redirect 57 | Примечание: Предполагается, что модуль `mod_rewrite` установлен и включен. 58 | 59 | ### Перенаправление с без www на с www 60 | ``` apacheconf 61 | RewriteEngine on 62 | RewriteCond %{HTTP_HOST} ^example\.com [NC] 63 | RewriteRule ^(.*)$ http://www.example.com/$1 [L,R=301,NC] 64 | ``` 65 | 66 | ### Перенаправление с без www на с www для HTTP или HTTPS 67 | ``` apacheconf 68 | RewriteCond %{HTTP_HOST} !^$ 69 | RewriteCond %{HTTP_HOST} !^www\. [NC] 70 | RewriteCond %{HTTPS}s ^on(s)| 71 | RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L] 72 | ``` 73 | Это работает для _любого_ домена. [Источник](https://stackoverflow.com/questions/4916222/htaccess-how-to-force-www-in-a-generic-way) 74 | 75 | ### Перенаправление с www на без www 76 | Это [вечная](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, но если вы поклонник "чистых" доменов, то: 77 | ``` apacheconf 78 | RewriteEngine on 79 | RewriteCond %{HTTP_HOST} ^www\.example\.com [NC] 80 | RewriteRule ^(.*)$ http://example.com/$1 [L,R=301] 81 | ``` 82 | 83 | ### Перенаправление с www на без www для HTTP или HTTPS 84 | ``` apacheconf 85 | RewriteEngine on 86 | RewriteCond %{HTTP_HOST} ^www\. 87 | RewriteCond %{HTTPS}s ^on(s)|off 88 | RewriteCond http%1://%{HTTP_HOST} ^(https?://)(www\.)?(.+)$ 89 | RewriteRule ^ %1%3%{REQUEST_URI} [R=301,L] 90 | ``` 91 | 92 | ### Принудительное использование HTTPS 93 | ``` apacheconf 94 | RewriteEngine on 95 | RewriteCond %{HTTPS} !on 96 | RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} 97 | 98 | # Примечание: Рекомендуется включить HTTP Strict Transport Security (HSTS) 99 | # на вашем HTTPS сайте для предотвращения атак посредника (man-in-the-middle). 100 | # https://developer.mozilla.org/en-US/docs/Web/Security/HTTP_strict_transport_security 101 | 102 | Header always set Strict-Transport-Security "max-age=31536000; includeSubDomains" 103 | 104 | ``` 105 | 106 | ### Принудительное использование HTTPS за прокси 107 | Полезно, если вы имеете прокси перед вашим сервером для TLS. 108 | ``` apacheconf 109 | RewriteCond %{HTTP:X-Forwarded-Proto} !https 110 | RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} 111 | ``` 112 | 113 | ### Вставить завершающий слэш 114 | ``` apacheconf 115 | RewriteCond %{REQUEST_URI} /+[^\.]+$ 116 | RewriteRule ^(.+[^/])$ %{REQUEST_URI}/ [R=301,L] 117 | ``` 118 | 119 | ### Удалить завершающий слэш 120 | Этот сниппет перенаправляет из пути, который заканчивается на слэш, на путь без завершающего слэша (кроме реальных директорий), например, из `http://www.example.com/blog/` перенаправит на `http://www.example.com/blog`. 121 | Это важно для SEO, так как [рекомендуется](http://overit.com/blog/canonical-urls), чтобы каждая страница имела канонический URL. 122 | ``` apacheconf 123 | RewriteCond %{REQUEST_FILENAME} !-d 124 | RewriteCond %{REQUEST_URI} (.+)/$ 125 | RewriteRule ^ %1 [R=301,L] 126 | ``` 127 | [Источник](https://stackoverflow.com/questions/21417263/htaccess-add-remove-trailing-slash-from-url#27264788) 128 | 129 | ### Редирект со страницы на страницу 130 | ``` apacheconf 131 | Redirect 301 /oldpage.html http://www.example.com/newpage.html 132 | Redirect 301 /oldpage2.html http://www.example.com/folder/ 133 | ``` 134 | [Источник](http://css-tricks.com/snippets/htaccess/301-redirects/) 135 | 136 | ### Редирект с использованием RedirectMatch 137 | ``` apacheconf 138 | RedirectMatch 301 /subdirectory(.*) http://www.newsite.com/newfolder/$1 139 | RedirectMatch 301 ^/(.*).htm$ /$1.html 140 | RedirectMatch 301 ^/200([0-9])/([^01])(.*)$ /$2$3 141 | RedirectMatch 301 ^/category/(.*)$ /$1 142 | RedirectMatch 301 ^/(.*)/htaccesselite-ultimate-htaccess-article.html(.*) /htaccess/htaccess.html 143 | RedirectMatch 301 ^/(.*).html/1/(.*) /$1.html$2 144 | RedirectMatch 301 ^/manual/(.*)$ http://www.php.net/manual/$1 145 | RedirectMatch 301 ^/dreamweaver/(.*)$ /tools/$1 146 | RedirectMatch 301 ^/z/(.*)$ http://static.askapache.com/$1 147 | ``` 148 | [Источник](http://www.askapache.com/htaccess/301-redirect-with-mod_rewrite-or-redirectmatch.html#301_Redirects_RedirectMatch) 149 | 150 | ### Алиас для определенной директории 151 | ``` apacheconf 152 | RewriteEngine On 153 | RewriteRule ^source-directory/(.*) /target-directory/$1 [R=301,L] 154 | ``` 155 | 156 | ### Алиас пути до скрипта 157 | ``` apacheconf 158 | FallbackResource /index.fcgi 159 | ``` 160 | В этом примере приведён файл `index.fcgi`, который лежит в каталоге и все запросы к этому каталогу, которые потерпели неудачу из-за отсутствия файла/директории будут перенаправлены на скрипт `index.fcgi`. Это хорошо, если вы хотите, чтобы `baz.foo/some/cool/path` обрабатывался скриптом `baz.foo/index.fcgi` (который также поддерживает запросы на `baz.foo`) в тоже время поддерживается `baz.foo/css/style.css` и другое подобное. Узнать истинный путь можно из переменной окружения PATH_INFO, которая доступна в скриптах. 161 | 162 | ``` apacheconf 163 | RewriteEngine On 164 | RewriteRule ^$ index.fcgi/ [QSA,L] 165 | RewriteCond %{REQUEST_FILENAME} !-f 166 | RewriteCond %{REQUEST_FILENAME} !-d 167 | RewriteRule ^(.*)$ index.fcgi/$1 [QSA,L] 168 | ``` 169 | Это менее эффективная версия директивы `FallbackResource` (поскольку использование `mod_rewrite` сложнее, чем просто обработка директивой `FallbackResource`), но также и более гибкое. 170 | 171 | ### Редирект всего сайта 172 | ``` apacheconf 173 | Redirect 301 / http://newsite.com/ 174 | ``` 175 | Этот сайт не "ломает" ссылки. Этот путь `www.oldsite.com/some/crazy/link.html` перенаправит вас на `www.newsite.com/some/crazy/link.html`. Это очень полезно, когда вы просто переносите сайт на новый домен. [Источник](http://css-tricks.com/snippets/htaccess/301-redirects/) 176 | 177 | ### Использовать чистые URL 178 | Этот сниппет позволяет использовать "чистые" URL -- без расширения .php, например, `example.com/users` вместо `example.com/users.php`. 179 | ``` apacheconf 180 | RewriteEngine On 181 | RewriteCond %{SCRIPT_FILENAME} !-d 182 | RewriteRule ^([^.]+)$ $1.php [NC,L] 183 | ``` 184 | [Источник](http://www.abeautifulsite.net/access-pages-without-the-php-extension-using-htaccess/) 185 | 186 | ## Безопасность 187 | ### Запретить доступ всем 188 | ``` apacheconf 189 | ## Apache 2.2 190 | Deny from all 191 | 192 | ## Apache 2.4 193 | # Require all denied 194 | ``` 195 | 196 | Подождите-ка, этот сниппет заблокирует доступ к сайту даже для вас! Сейчас исправим это... 197 | 198 | ### Запретить доступ всем, кроме... 199 | ``` apacheconf 200 | ## Apache 2.2 201 | Order deny,allow 202 | Deny from all 203 | Allow from xxx.xxx.xxx.xxx 204 | 205 | ## Apache 2.4 206 | # Require all denied 207 | # Require ip xxx.xxx.xxx.xxx 208 | ``` 209 | `xxx.xxx.xxx.xxx` - это ваш IP. Если вы замените последние три цифры, например, на `0/12`, этим вы определите диапазон IP внутри этой сети и это оградит вас от проблемы перечислять по отдельности все разрешённые IP. [Источник](http://speckyboy.com/2013/01/08/useful-htaccess-snippets-and-hacks/) 210 | 211 | И, естественно, противоположная функция к этой: 212 | 213 | ### Разрешить доступ всем, кроме... 214 | ``` apacheconf 215 | ## Apache 2.2 216 | Order deny,allow 217 | Deny from xxx.xxx.xxx.xxx 218 | Deny from xxx.xxx.xxx.xxy 219 | 220 | ## Apache 2.4 221 | # Require all granted 222 | # Require not ip xxx.xxx.xxx.xxx 223 | # Require not ip xxx.xxx.xxx.xxy 224 | ``` 225 | 226 | ### Запретить доступ к скрытым файлам и директориям 227 | Скрытые файлы и директории (те, чьи имена начинаются с точки `.`) должны в большинстве, если не все, быть недоступны для других. Например: `.htaccess`, `.htpasswd`, `.git`, `.hg`... 228 | ``` apacheconf 229 | RewriteCond %{SCRIPT_FILENAME} -d [OR] 230 | RewriteCond %{SCRIPT_FILENAME} -f 231 | RewriteRule "(^|/)\." - [F] 232 | ``` 233 | 234 | Как вариант, вы можете показывать ошибку Not Found (не найдено), чтобы не давать атакующему подсказку: 235 | ``` apacheconf 236 | RedirectMatch 404 /\..*$ 237 | ``` 238 | 239 | ### Запретить доступ к файлам 240 | Эти файлы могут быть оставлены некоторыми редакторами text/html (вроде Vi/Vim) и представляют огромную дыру в безопасности, если станут общедоступными. 241 | ``` apacheconf 242 | 243 | ## Apache 2.2 244 | Order allow,deny 245 | Deny from all 246 | Satisfy All 247 | 248 | ## Apache 2.4 249 | # Require all denied 250 | 251 | ``` 252 | [Источник](https://github.com/h5bp/server-configs-apache) 253 | 254 | ### Запретить листинг директорий 255 | ``` apacheconf 256 | Options All -Indexes 257 | ``` 258 | 259 | ### Запретить хотлинкинг изображений 260 | ``` apacheconf 261 | RewriteEngine on 262 | # Удалите эту строчку, если вы хотите заблокировать пользователя с пустым Referrer 263 | RewriteCond %{HTTP_REFERER} !^$ 264 | 265 | RewriteCond %{HTTP_REFERER} !^https?://(.+\.)?example.com [NC] 266 | RewriteRule \.(jpe?g|png|gif|bmp)$ - [NC,F,L] 267 | 268 | # Если вы захотите отображать вместо заблокированного изображения свой баннер, 269 | # то замените правило выше на это: 270 | # RewriteRule \.(jpe?g|png|gif|bmp) http://example.com/blocked.png [R,L] 271 | ``` 272 | 273 | ### Запретить хотлинкинг изображений для определенных доменов 274 | Иногда вам потребуется запретить хотлинкинг только для некоторых доменов. 275 | ``` apacheconf 276 | RewriteEngine on 277 | RewriteCond %{HTTP_REFERER} ^https?://(.+\.)?badsite\.com [NC,OR] 278 | RewriteCond %{HTTP_REFERER} ^https?://(.+\.)?badsite2\.com [NC,OR] 279 | RewriteRule \.(jpe?g|png|gif|bmp)$ - [NC,F,L] 280 | 281 | # Если вы захотите отображать вместо заблокированного изображения свой баннер, 282 | # то замените правило выше на это: 283 | # RewriteRule \.(jpe?g|png|gif|bmp) http://example.com/blocked.png [R,L] 284 | ``` 285 | 286 | ### Защитить паролем директорию 287 | Сначала нужно создать файл `.htpasswd` в определенной директории: 288 | ``` bash 289 | htpasswd -c /home/fellowship/.htpasswd ваш_суперсекретный_пароль 290 | ``` 291 | 292 | И потом использовать этот файл для аутентификации: 293 | ``` apacheconf 294 | AuthType Basic 295 | AuthName "One does not simply" 296 | AuthUserFile /home/fellowship/.htpasswd 297 | Require valid-user 298 | ``` 299 | 300 | ### Защитить паролем один или несколько файлов 301 | ``` apacheconf 302 | AuthName "One still does not simply" 303 | AuthType Basic 304 | AuthUserFile /home/fellowship/.htpasswd 305 | 306 | 307 | Require valid-user 308 | 309 | 310 | 311 | Require valid-user 312 | 313 | ``` 314 | 315 | ### Заблокировать посетителя по Referrer 316 | Блокирует доступ для всех пользователей, которые пришли (были перенаправлены) из определенного домена(-ов). 317 | [Источник](http://www.htaccess-guide.com/deny-visitors-by-referrer/) 318 | ``` apacheconf 319 | RewriteEngine on 320 | # Options +FollowSymlinks 321 | RewriteCond %{HTTP_REFERER} somedomain\.com [NC,OR] 322 | RewriteCond %{HTTP_REFERER} anotherdomain\.com 323 | RewriteRule .* - [F] 324 | ``` 325 | 326 | ### Запретить рендеринг сайта во фрейме 327 | Этот сниппет запрещает отображение сайта во фрейме (например, в теге `iframe`), но разрешает отображение сайта во фрейме для определенных URI. 328 | ``` apacheconf 329 | SetEnvIf Request_URI "/starry-night" allow_framing=true 330 | Header set X-Frame-Options SAMEORIGIN env=!allow_framing 331 | ``` 332 | 333 | ## Производительность 334 | ### Сжатие текстовых файлов 335 | ``` apacheconf 336 | 337 | 338 | # Принудительное сжатие для исковерканных заголовков. 339 | # https://developer.yahoo.com/blogs/ydn/pushing-beyond-gzipping-25601.html 340 | 341 | 342 | SetEnvIfNoCase ^(Accept-EncodXng|X-cept-Encoding|X{15}|~{15}|-{15})$ ^((gzip|deflate)\s*,?\s*)+|[X~-]{4,13}$ HAVE_Accept-Encoding 343 | RequestHeader append Accept-Encoding "gzip,deflate" env=HAVE_Accept-Encoding 344 | 345 | 346 | 347 | # Сжимать исходящие данные с одним из следующих MIME типов 348 | # (для Apache ниже версии 2.3.7 не нужно включать `mod_filter` 349 | # и вы можете удалить строки `` и `` 350 | # так как `AddOutputFilterByType` все еще есть в ядре Apache). 351 | 352 | AddOutputFilterByType DEFLATE application/atom+xml \ 353 | application/javascript \ 354 | application/json \ 355 | application/rss+xml \ 356 | application/vnd.ms-fontobject \ 357 | application/x-font-ttf \ 358 | application/x-web-app-manifest+json \ 359 | application/xhtml+xml \ 360 | application/xml \ 361 | font/opentype \ 362 | image/svg+xml \ 363 | image/x-icon \ 364 | text/css \ 365 | text/html \ 366 | text/plain \ 367 | text/x-component \ 368 | text/xml 369 | 370 | 371 | 372 | ``` 373 | [Источник](https://github.com/h5bp/server-configs-apache) 374 | 375 | 376 | ### Установить Expires Headers 377 | _Expires headers_ говорят браузеру, должен ли он загружать файл из сервера или же из кэша. Для статичного контента рекомендуется установить `Expires` заголовки на что-нибудь далекое в будущем. 378 | 379 | Если вы не контролируете изменение версий с помощью перебора, основанного на файлах, подумайте о том, чтобы уменьшить время кэша для CSS и JS, например, до 1 недели. [Источник](https://github.com/h5bp/server-configs-apache) 380 | ``` apacheconf 381 | 382 | ExpiresActive on 383 | ExpiresDefault "access plus 1 month" 384 | 385 | # CSS 386 | ExpiresByType text/css "access plus 1 year" 387 | 388 | # Данные 389 | ExpiresByType application/json "access plus 0 seconds" 390 | ExpiresByType application/xml "access plus 0 seconds" 391 | ExpiresByType text/xml "access plus 0 seconds" 392 | 393 | # Favicon 394 | ExpiresByType image/x-icon "access plus 1 week" 395 | 396 | # HTML компоненты (HTCs) 397 | ExpiresByType text/x-component "access plus 1 month" 398 | 399 | # HTML 400 | ExpiresByType text/html "access plus 0 seconds" 401 | 402 | # JavaScript 403 | ExpiresByType application/javascript "access plus 1 year" 404 | 405 | # Файлы манифеста (Manifest) 406 | ExpiresByType application/x-web-app-manifest+json "access plus 0 seconds" 407 | ExpiresByType text/cache-manifest "access plus 0 seconds" 408 | 409 | # Медиа 410 | ExpiresByType audio/ogg "access plus 1 month" 411 | ExpiresByType image/gif "access plus 1 month" 412 | ExpiresByType image/jpeg "access plus 1 month" 413 | ExpiresByType image/png "access plus 1 month" 414 | ExpiresByType video/mp4 "access plus 1 month" 415 | ExpiresByType video/ogg "access plus 1 month" 416 | ExpiresByType video/webm "access plus 1 month" 417 | 418 | # Фиды 419 | ExpiresByType application/atom+xml "access plus 1 hour" 420 | ExpiresByType application/rss+xml "access plus 1 hour" 421 | 422 | # Web шрифты 423 | ExpiresByType application/font-woff2 "access plus 1 month" 424 | ExpiresByType application/font-woff "access plus 1 month" 425 | ExpiresByType application/vnd.ms-fontobject "access plus 1 month" 426 | ExpiresByType application/x-font-ttf "access plus 1 month" 427 | ExpiresByType font/opentype "access plus 1 month" 428 | ExpiresByType image/svg+xml "access plus 1 month" 429 | 430 | ``` 431 | 432 | ### Выключить eTags 433 | Удаляя заголовок `ETag`, вы выключаете кэш и избавляете возможности проверять браузером файлы, следовательно они будут полагаться на заголовки `Cache-Control` и `Expires`. [Источник](http://www.askapache.com/htaccess/apache-speed-etags.html) 434 | ``` apacheconf 435 | 436 | Header unset ETag 437 | 438 | FileETag None 439 | ``` 440 | 441 | ## Разное 442 | 443 | ### Настройка PHP 444 | ``` apacheconf 445 | php_value 446 | 447 | # Например: 448 | php_value upload_max_filesize 50M 449 | php_value max_execution_time 240 450 | ``` 451 | 452 | ### Пользовательские страницы ошибок 453 | ``` apacheconf 454 | ErrorDocument 500 "Хьюстон, у нас проблемы." 455 | ErrorDocument 401 http://error.example.com/mordor.html 456 | ErrorDocument 404 /errors/halflife3.html 457 | ``` 458 | 459 | ### Принудительная загрузка (скачивать файл вместо отображения в браузере) 460 | Иногда нужно загрузить запрашиваемый файл, а не отображать его в браузере. 461 | ``` apacheconf 462 | 463 | ForceType application/octet-stream 464 | Header set Content-Disposition attachment 465 | 466 | ``` 467 | 468 | А ниже сниппет, который делает это с точностью до наоборот: 469 | 470 | ### Запретить загрузку (отображать plain в браузере) 471 | Иногда нужно отобразить запрашиваемый файл в браузере, а не загружать его. 472 | ``` apacheconf 473 | 474 | Header set Content-Type text/plain 475 | 476 | ``` 477 | 478 | ### Разрешить кроссдоменные шрифты 479 | Шрифты, которые хранятся на CDN серверах, могут не работать в Firefox и IE из-за [CORS](https://ru.wikipedia.org/wiki/Cross-origin_resource_sharing). Данный сниппет решает эту проблему. 480 | ``` apacheconf 481 | 482 | 483 | Header set Access-Control-Allow-Origin "*" 484 | 485 | 486 | ``` 487 | [Источник](https://github.com/h5bp/server-configs-apache/issues/32) 488 | 489 | ### Установить по умолчанию кодировку UTF-8 490 | Ваш текстовый контент должен быть всегда закодирован в UTF-8, не так ли? 491 | ``` apacheconf 492 | # Используйте кодировку UTF-8 для обработки text/plain или text/html 493 | AddDefaultCharset utf-8 494 | 495 | # Принудительное использование UTF-8 для различных файлов 496 | AddCharset utf-8 .atom .css .js .json .rss .vtt .xml 497 | ``` 498 | [Источник](https://github.com/h5bp/server-configs-apache) 499 | 500 | ### Переключиться на другую версию PHP 501 | Если вы используете шаред хостинг, вполне вероятно, что там установлено несколько версий PHP. Но вам нужна конкретная версия PHP для вашего веб-сайта. Этот сниппет должен переключить PHP версию. 502 | 503 | ``` apacheconf 504 | AddHandler application/x-httpd-php56 .php 505 | 506 | # В качестве альтернативы вы можете использовать AddType 507 | AddType application/x-httpd-php56 .php 508 | ``` 509 | 510 | ### Выключить просмотр в режиме совместимости в Internet Explorer 511 | Просмотр в режиме совместимости в IE может оказать влияние на то, как отображаются некоторые сайты. Этот сниппет заставляет IE использовать движок Edge Rendering и выключает просмотр в режиме совместимости. 512 | 513 | ``` apacheconf 514 | 515 | BrowserMatch MSIE is-msie 516 | Header set X-UA-Compatible IE=edge env=is-msie 517 | 518 | ``` 519 | 520 | ### Обработка WebP изображений 521 | Если [WebP изображения](https://developers.google.com/speed/webp/?csw=1) поддерживаюся и изображения с расширениями .webp и теми же именами найдены в том же месте, где и изображения jpg/png, которые нужно отправить, то тогда вместо них отправляются изображения WebP. 522 | 523 | ``` apacheconf 524 | RewriteEngine On 525 | RewriteCond %{HTTP_ACCEPT} image/webp 526 | RewriteCond %{DOCUMENT_ROOT}/$1.webp -f 527 | RewriteRule (.+)\.(jpe?g|png)$ $1.webp [T=image/webp,E=accept:1] 528 | ``` 529 | [Источник](https://github.com/vincentorback/WebP-images-with-htaccess) 530 | -------------------------------------------------------------------------------- /Translations/Slovak/README.md: -------------------------------------------------------------------------------- 1 | # .htaccess Ukážky kódov 2 | 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`. 3 | 4 | **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. 5 | 6 | **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). 7 | 8 | ## Tabuľka obsahu 9 | - [Prepisovanie a presmerovanie](#prepisovanie-a-presmerovanie) 10 | - [Presmerovanie na WWW](#presmerovanie-na-www) 11 | - [Všeobecné presmerovanie na WWW](#v-eobecn-presmerovanie-na-www) 12 | - [Presmerovanie bez WWW](#presmerovanie-bez-www) 13 | - [Presmerovanie na HTTPS](#presmerovanie-na-https) 14 | - [Pridanie koncového lomítka](#pridanie-koncov-ho-lom-tka) 15 | - [Presmerovanie jednej stránky](#presmerovanie-jednej-str-nky) 16 | - [Presmerovanie celého webu](#presmerovanie-cel-ho-webu) 17 | - [Bezpečnosť](#bezpe-nos) 18 | - [Zakázanie prístupu pre všetkých](#zak-zanie-pr-stupu-pre-v-etk-ch) 19 | - [Zakázanie prístupu všetkým okrem vás](#zak-zanie-pr-stupu-v-etk-m-okrem-v-s) 20 | - [Povoliť prístup všetkým, ale nie spamerom](#povoli-pr-stup-v-etk-m-ale-nie-spamerom) 21 | - [Zakázať prístup k skrytým súborom a priečinkom](#zak-za-pr-stup-k-skryt-m-s-borom-a-prie-inkom) 22 | - [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) 23 | - [Zakázanie prehliadania priečinka](#zak-zanie-prehliadania-prie-inka) 24 | - [Zakázanie hotlinkovania obrázkov](#zak-zanie-hotlinkovania-obr-zkov) 25 | - [Priečinok chránený heslom](#prie-inok-chr-nen-heslom) 26 | - [Súbor alebo niekoľko súborov chránených heslom](#s-bor-alebo-nieko-ko-s-borov-chr-nen-ch-heslom) 27 | - [Výkon](#v-kon) 28 | - [Kompresia textových súborov](#kompresia-textov-ch-s-borov) 29 | - [Nastavenia expirácie headerov](#nastavenia-expir-cie-headerov) 30 | - [Vypnutie eTags](#vypnutie-etags) 31 | - [Ostatné](#ostatn) 32 | - [Nastavenie PHP premenných](#nastavenie-php-premenn-ch) 33 | - [Vlastné chybové stránky](#vlastn-chybov-str-nky) 34 | - [Povinné stiahnutie](#povinn-stiahnutie) 35 | - [Povoliť cross-domain písma](#povoli-cross-domain-p-sma) 36 | - [Automatické UTF-8 kódovanie](#automatick-utf-8-k-dovanie) 37 | 38 | ## Prepisovanie a presmerovanie 39 | Poznámka: Predpokladá sa, že máte nainštalovaný a povolený `mod_rewrite`. 40 | 41 | ### Presmerovanie na WWW 42 | ``` apacheconf 43 | RewriteEngine on 44 | RewriteCond %{HTTP_HOST} ^example\.com [NC] 45 | RewriteRule ^(.*)$ http://www.example.com/$1 [L,R=301,NC] 46 | ``` 47 | 48 | ### Všeobecné presmerovanie na WWW 49 | ``` apacheconf 50 | RewriteCond %{HTTP_HOST} !^$ 51 | RewriteCond %{HTTP_HOST} !^www\. [NC] 52 | RewriteCond %{HTTPS}s ^on(s)| 53 | RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L] 54 | ``` 55 | Funguje pre _akúkoľvek_ doménu. [Source](https://stackoverflow.com/questions/4916222/htaccess-how-to-force-www-in-a-generic-way) 56 | 57 | ### Presmerovanie bez WWW 58 | Je [odporúčané](http://no-www.org/) vymazať `www` z vašej domény. Prekvapenie prekvapenie! 59 | ``` apacheconf 60 | RewriteEngine on 61 | RewriteCond %{HTTP_HOST} ^www\.example\.com [NC] 62 | RewriteRule ^(.*)$ http://example.com/$1 [L,R=301] 63 | ``` 64 | 65 | ### Presmerovanie na HTTPS 66 | ``` apacheconf 67 | RewriteEngine on 68 | RewriteCond %{HTTPS} !on 69 | RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} 70 | ``` 71 | 72 | ### Pridanie koncového lomítka 73 | ``` apacheconf 74 | RewriteCond %{REQUEST_URI} /+[^\.]+$ 75 | RewriteRule ^(.+[^/])$ %{REQUEST_URI}/ [R=301,L] 76 | ``` 77 | 78 | ### Presmerovanie jednej stránky 79 | ``` apacheconf 80 | Redirect 301 /oldpage.html http://www.yoursite.com/newpage.html 81 | Redirect 301 /oldpage2.html http://www.yoursite.com/folder/ 82 | ``` 83 | [Zdroj](http://css-tricks.com/snippets/htaccess/301-redirects/) 84 | 85 | ### Presmerovanie celého webu 86 | ``` apacheconf 87 | Redirect 301 / http://newsite.com/ 88 | ``` 89 | 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/) 90 | 91 | ## Bezpečnosť 92 | ### Zakázanie prístupu pre všetkých 93 | ``` apacheconf 94 | Deny from All 95 | ``` 96 | 97 | Ale pozor, toto zakáže prístup aj vám! 98 | 99 | ### Zakázanie prístupu všetkým okrem vás 100 | ``` apacheconf 101 | Order deny, allow 102 | Deny from All 103 | Allow from xxx.xxx.xxx.xxx 104 | ``` 105 | `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/) 106 | 107 | Samozrejme je tu aj opačná verzia: 108 | 109 | ### Povoliť prístup všetkým, ale nie spamerom 110 | ``` apacheconf 111 | Order deny, allow 112 | Deny from xxx.xxx.xxx.xxx 113 | Deny from xxx.xxx.xxx.xxy 114 | ``` 115 | 116 | ### Zakázať prístup k skrytým súborom a priečinkom 117 | 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`... 118 | ``` apacheconf 119 | RewriteCond %{SCRIPT_FILENAME} -d [OR] 120 | RewriteCond %{SCRIPT_FILENAME} -f 121 | RewriteRule "(^|/)\." - [F] 122 | ``` 123 | 124 | Ako alternatívu môžte použíť `Not Found` chybu, pri ktorej nemá útočník ani potuchy: 125 | ``` apacheconf 126 | RedirectMatch 404 /\..*$ 127 | ``` 128 | 129 | ### Zakázanie prístupu k zálohám a zdrojovým súborom 130 | 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. 131 | ``` apacheconf 132 | 133 | Order allow,deny 134 | Deny from all 135 | Satisfy All 136 | 137 | ``` 138 | [Zdroj](http://h5bp.com) 139 | 140 | ### Zakázanie prehliadania priečinka 141 | ``` apacheconf 142 | Options All -Indexes 143 | ``` 144 | 145 | ### Zakázanie hotlinkovania obrázkov 146 | ``` apacheconf 147 | RewriteEngine on 148 | RewriteCond %{HTTP_REFERER} !^$ 149 | RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?yourdomain.com [NC] 150 | RewriteRule \.(jpg|jpeg|png|gif)$ - [NC,F,L] 151 | ``` 152 | 153 | ### Priečinok chránený heslom 154 | Ako prvé potrebujete vytvoriť `.htpasswd` súbor niekde v systéme: 155 | ``` bash 156 | htpasswd -c /home/fellowship/.htpasswd boromir 157 | ``` 158 | 159 | Potom to môžte použiť na autentifikáciu: 160 | ``` apacheconf 161 | AuthType Basic 162 | AuthName "One does not simply" 163 | AuthUserFile /home/fellowship/.htpasswd 164 | Require valid-user 165 | ``` 166 | 167 | ### Súbor alebo niekoľko súborov chránených heslom 168 | ``` apacheconf 169 | AuthName "One still does not simply" 170 | AuthType Basic 171 | AuthUserFile /home/fellowship/.htpasswd 172 | 173 | 174 | Require valid-user 175 | 176 | 177 | 178 | Require valid-user 179 | 180 | ``` 181 | 182 | ## Výkon 183 | ### Kompresia textových súborov 184 | ``` apacheconf 185 | 186 | 187 | # "Tvrdá" kompresia pre pozmenené hlavičky 188 | # https://developer.yahoo.com/blogs/ydn/pushing-beyond-gzipping-25601.html 189 | 190 | 191 | SetEnvIfNoCase ^(Accept-EncodXng|X-cept-Encoding|X{15}|~{15}|-{15})$ ^((gzip|deflate)\s*,?\s*)+|[X~-]{4,13}$ HAVE_Accept-Encoding 192 | RequestHeader append Accept-Encoding "gzip,deflate" env=HAVE_Accept-Encoding 193 | 194 | 195 | 196 | # Komprimovať všetky výstup s týmito konkrétnymi MIME-typmi 197 | # (pre Apache verzie pod 2.3.7, nepotrebujete povoľovať `mod_filter` 198 | # a môžte vymazať `` a `` riadky 199 | # ale `AddOutputFilterByType` je stále jedna zo základných smerníc). 200 | 201 | AddOutputFilterByType DEFLATE application/atom+xml \ 202 | application/javascript \ 203 | application/json \ 204 | application/rss+xml \ 205 | application/vnd.ms-fontobject \ 206 | application/x-font-ttf \ 207 | application/x-web-app-manifest+json \ 208 | application/xhtml+xml \ 209 | application/xml \ 210 | font/opentype \ 211 | image/svg+xml \ 212 | image/x-icon \ 213 | text/css \ 214 | text/html \ 215 | text/plain \ 216 | text/x-component \ 217 | text/xml 218 | 219 | 220 | 221 | ``` 222 | [Zdroj](https://h5bp.com) 223 | 224 | 225 | ### Nastavenia expirácie headerov 226 | _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. 227 | 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) 228 | ``` apacheconf 229 | 230 | ExpiresActive on 231 | ExpiresDefault "access plus 1 month" 232 | 233 | # CSS 234 | ExpiresByType text/css "access plus 1 year" 235 | 236 | # Data interchange 237 | ExpiresByType application/json "access plus 0 seconds" 238 | ExpiresByType application/xml "access plus 0 seconds" 239 | ExpiresByType text/xml "access plus 0 seconds" 240 | 241 | # Favicon (cannot be renamed!) 242 | ExpiresByType image/x-icon "access plus 1 week" 243 | 244 | # HTML components (HTCs) 245 | ExpiresByType text/x-component "access plus 1 month" 246 | 247 | # HTML 248 | ExpiresByType text/html "access plus 0 seconds" 249 | 250 | # JavaScript 251 | ExpiresByType application/javascript "access plus 1 year" 252 | 253 | # Manifest files 254 | ExpiresByType application/x-web-app-manifest+json "access plus 0 seconds" 255 | ExpiresByType text/cache-manifest "access plus 0 seconds" 256 | 257 | # Media 258 | ExpiresByType audio/ogg "access plus 1 month" 259 | ExpiresByType image/gif "access plus 1 month" 260 | ExpiresByType image/jpeg "access plus 1 month" 261 | ExpiresByType image/png "access plus 1 month" 262 | ExpiresByType video/mp4 "access plus 1 month" 263 | ExpiresByType video/ogg "access plus 1 month" 264 | ExpiresByType video/webm "access plus 1 month" 265 | 266 | # Web feeds 267 | ExpiresByType application/atom+xml "access plus 1 hour" 268 | ExpiresByType application/rss+xml "access plus 1 hour" 269 | 270 | # Web fonts 271 | ExpiresByType application/font-woff "access plus 1 month" 272 | ExpiresByType application/vnd.ms-fontobject "access plus 1 month" 273 | ExpiresByType application/x-font-ttf "access plus 1 month" 274 | ExpiresByType font/opentype "access plus 1 month" 275 | ExpiresByType image/svg+xml "access plus 1 month" 276 | 277 | ``` 278 | 279 | ### Vypnutie eTags 280 | 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) 281 | ``` apacheconf 282 | 283 | Header unset ETag 284 | 285 | FileETag None 286 | ``` 287 | 288 | 289 | ## Ostatné 290 | 291 | ### Nastavenie PHP premenných 292 | ``` apacheconf 293 | php_value 294 | 295 | # Príklad: 296 | php_value upload_max_filesize 50M 297 | php_value max_execution_time 240 298 | ``` 299 | 300 | ### Vlastné chybové stránky 301 | ``` apacheconf 302 | ErrorDocument 400 /errors/breakingbad.html 303 | ErrorDocument 401 /errors/notrespassing.html 304 | ErrorDocument 403 /errors/mordor.html 305 | ErrorDocument 404 /errors/halflife3.html 306 | ErrorDocument 500 /errors/notabugitsafeature.html 307 | ``` 308 | 309 | ### Povinné stiahnutie 310 | Niekedy chcete aby preliadač stiahol obsah namiesto jeho zobrazenia. Toto slúži presne na to. 311 | ``` apacheconf 312 | 313 | ForceType application/octet-stream 314 | Header set Content-Disposition attachment 315 | 316 | ``` 317 | 318 | ### Povoliť cross-domain písma 319 | 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ť. 320 | ``` apacheconf 321 | 322 | 323 | Header set Access-Control-Allow-Origin "*" 324 | 325 | 326 | ``` 327 | 328 | ### Automatické UTF-8 kódovanie 329 | Tvoj text by sa mal vždy kódovať v UTF-8, nie? 330 | ``` apacheconf 331 | # Použiť UTF-8 kódovanie pre všetky súbory typu text/plain a text/html 332 | AddDefaultCharset utf-8 333 | 334 | # Nastavenie UTF-8 pre niekoľko formátov súborov 335 | AddCharset utf-8 .atom .css .js .json .rss .vtt .xml 336 | ``` 337 | [Zdroj](http://h5bp.com) 338 | --------------------------------------------------------------------------------