Htaccess для Joomla, который работает. Правильный htaccess для joomla 3


Joomla 2.5-3.x - оригинальный htaccess — Wiki - Iphoster

Самые выгодные сервера‎

Joomla 2.5-3.x - оригинальный htaccess

Joomla 2.5-3.x - оригинальный htaccess можно скачать/скопировать тут:

## # @package Joomla # @copyright Copyright (C) 2005 - 2012 Open Source Matters. All rights reserved. # @license GNU General Public License version 2 or later; see LICENSE.txt ##

## # READ THIS COMPLETELY IF YOU CHOOSE TO USE THIS FILE! # # The line just below this section: 'Options +FollowSymLinks' may cause problems # with some server configurations. It is required for use of mod_rewrite, but may already # be set by your server administrator in a way that dissallows changing it in # your .htaccess file. If using it causes your server to error out, comment it out (add # to # beginning of line), reload your site in your browser and test your sef url's. If they work, # it has been set by your server administrator and you do not need it set here. ##

## Can be commented out if causes errors, see notes above. Options +FollowSymLinks

## Mod_rewrite in use.

RewriteEngine On

## Begin - Rewrite rules to block out some common exploits. # If you experience problems on your site block out the operations listed below # This attempts to block the most common type of exploit `attempts` to Joomla! # # Block out any script trying to base64_encode data within the URL. RewriteCond %{QUERY_STRING} base64_encode[^(]*\([^)]*\) [OR] # Block out any script that includes a <script> tag in URL. RewriteCond %{QUERY_STRING} (<|%3C)([^s]*s)+cript.*(>|%3E) [NC,OR] # Block out any script trying to set a PHP GLOBALS variable via URL. RewriteCond %{QUERY_STRING} GLOBALS(=|\[|\%[0-9A-Z]{0,2}) [OR] # Block out any script trying to modify a _REQUEST variable via URL. RewriteCond %{QUERY_STRING} _REQUEST(=|\[|\%[0-9A-Z]{0,2}) # Return 403 Forbidden header and show the content of the root homepage RewriteRule .* index.php [F] # ## End - Rewrite rules to block out some common exploits.

## Begin - Custom redirects # # If you need to redirect some pages, or set a canonical non-www to # www redirect (or vice versa), place that code here. Ensure those # redirects use the correct RewriteRule syntax and the [R=301,L] flags. # ## End - Custom redirects

## # Uncomment following line if your webserver's URL # is not directly related to physical file paths. # Update Your Joomla! Directory (just / for root). ##

# RewriteBase /

## Begin - Joomla! core SEF Section. # RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] # # If the requested path and file is not /index.php and the request # has not already been internally rewritten to the index.php script RewriteCond %{REQUEST_URI} !^/index\.php # and the request is for something within the component folder, # or for the site root, or for an extensionless URL, or the # requested URL ends with one of the listed extensions RewriteCond %{REQUEST_URI} /component/|(/[^.]*|\.(php|html?|feed|pdf|vcf|raw))$ [NC] # and the requested path and file doesn't directly match a physical file RewriteCond %{REQUEST_FILENAME} !-f # and the requested path and file doesn't directly match a physical folder RewriteCond %{REQUEST_FILENAME} !-d # internally rewrite the request to the index.php script RewriteRule .* index.php [L] # ## End - Joomla! core SEF Section.

wiki.iphoster.net

Оригинальный правильный .htaccess Joomla, Wordpress, MODX, Bitrix, Drupal, Simpla

In&nbspВебмастеру On&nbsp21.09.2016 &nbsp

.htaccess Joomla 2.5-3

### @package Joomla# @copyright Copyright (C) 2005 — 2012 Open Source Matters. All rights reserved.# @license GNU General Public License version 2 or later; see LICENSE.txt##

### READ THIS COMPLETELY IF YOU CHOOSE TO USE THIS FILE!## The line just below this section: ‘Options +FollowSymLinks’ may cause problems# with some server configurations. It is required for use of mod_rewrite, but may already# be set by your server administrator in a way that dissallows changing it in# your .htaccess file. If using it causes your server to error out, comment it out (add # to# beginning of line), reload your site in your browser and test your sef url’s. If they work,# it has been set by your server administrator and you do not need it set here.##

## Can be commented out if causes errors, see notes above.Options +FollowSymLinks

## Mod_rewrite in use.

RewriteEngine On

## Begin — Rewrite rules to block out some common exploits.# If you experience problems on your site block out the operations listed below# This attempts to block the most common type of exploit `attempts` to Joomla!## Block out any script trying to base64_encode data within the URL.RewriteCond %{QUERY_STRING} base64_encode[^(]*\([^)]*\) [OR]# Block out any script that includes a <script> tag in URL.RewriteCond %{QUERY_STRING} (<|%3C)([^s]*s)+cript.*(>|%3E) [NC,OR]# Block out any script trying to set a PHP GLOBALS variable via URL.RewriteCond %{QUERY_STRING} GLOBALS(=|\[|\%[0-9A-Z]{0,2}) [OR]# Block out any script trying to modify a _REQUEST variable via URL.RewriteCond %{QUERY_STRING} _REQUEST(=|\[|\%[0-9A-Z]{0,2})# Return 403 Forbidden header and show the content of the root homepageRewriteRule .* index.php [F]### End — Rewrite rules to block out some common exploits.

## Begin — Custom redirects## If you need to redirect some pages, or set a canonical non-www to# www redirect (or vice versa), place that code here. Ensure those# redirects use the correct RewriteRule syntax and the [R=301,L] flags.### End — Custom redirects

### Uncomment following line if your webserver’s URL# is not directly related to physical file paths.# Update Your Joomla! Directory (just / for root).##

# RewriteBase /

## Begin — Joomla! core SEF Section.#RewriteRule .* — [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]## If the requested path and file is not /index.php and the request# has not already been internally rewritten to the index.php scriptRewriteCond %{REQUEST_URI} !^/index\.php# and the request is for something within the component folder,# or for the site root, or for an extensionless URL, or the# requested URL ends with one of the listed extensionsRewriteCond %{REQUEST_URI} /component/|(/[^.]*|\.(php|html?|feed|pdf|vcf|raw))$ [NC]# and the requested path and file doesn’t directly match a physical fileRewriteCond %{REQUEST_FILENAME} !-f# and the requested path and file doesn’t directly match a physical folderRewriteCond %{REQUEST_FILENAME} !-d# internally rewrite the request to the index.php scriptRewriteRule .* index.php [L]### End — Joomla! core SEF Section.

.htaccess Joomla 1.5

### @version $Id: htaccess.txt 21064 2011-04-03 22:12:19Z dextercowley $# @package Joomla# @copyright Copyright (C) 2005 — 2010 Open Source Matters. All rights reserved.# @license http://www.gnu.org/copyleft/gpl.html GNU/GPL# Joomla! is Free Software##

###################################################### READ THIS COMPLETELY IF YOU CHOOSE TO USE THIS FILE## The line just below this section: ‘Options +FollowSymLinks’ may cause problems# with some server configurations. It is required for use of mod_rewrite, but may already# be set by your server administrator in a way that dissallows changing it in# your .htaccess file. If using it causes your server to error out, comment it out (add # to# beginning of line), reload your site in your browser and test your sef url’s. If they work,# it has been set by your server administrator and you do not need it set here.######################################################

## Can be commented out if causes errors, see notes above.Options +FollowSymLinks

## mod_rewrite in use

RewriteEngine On

########## Begin — Rewrite rules to block out some common exploits## If you experience problems on your site block out the operations listed below## This attempts to block the most common type of exploit `attempts` to Joomla!### Deny access to extension xml files (uncomment out to activate)#<Files ~ «\.xml$»>#Order allow,deny#Deny from all#Satisfy all#</Files>## End of deny access to extension xml files# Block out any script trying to set a mosConfig value through the URLRewriteCond %{QUERY_STRING} mosConfig_[a-zA-Z_]{1,21}(=|\%3D) [OR]# Block out any script trying to base64_encode data within the URLRewriteCond %{QUERY_STRING} base64_encode[^(]*\([^)]*\) [OR]# Block out any script that includes a <script> tag in URLRewriteCond %{QUERY_STRING} (<|%3C)([^s]*s)+cript.*(>|%3E) [NC,OR]# Block out any script trying to set a PHP GLOBALS variable via URLRewriteCond %{QUERY_STRING} GLOBALS(=|\[|\%[0-9A-Z]{0,2}) [OR]# Block out any script trying to modify a _REQUEST variable via URLRewriteCond %{QUERY_STRING} _REQUEST(=|\[|\%[0-9A-Z]{0,2})# Return 403 Forbidden header and show the content of the root homepageRewriteRule .* index.php [F]########### End — Rewrite rules to block out some common exploits

########## Begin — Custom redirects## If you need to redirect some pages, or set a canonical non-www to# www redirect (or vice versa), place that code here. Ensure those# redirects use the correct RewriteRule syntax and the [R=301,L] flags.########### End — Custom redirects

# Uncomment following line if your webserver’s URL# is not directly related to physical file paths.# Update Your Joomla! Directory (just / for root)

# RewriteBase /

########## Begin — Joomla! core SEF Section#RewriteRule .* — [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]## If the requested path and file is not /index.php and the request# has not already been internally rewritten to the index.php scriptRewriteCond %{REQUEST_URI} !^/index\.php# and the request is for root, or for an extensionless URL, or the# requested URL ends with one of the listed extensionsRewriteCond %{REQUEST_URI} (/[^.]*|\.(php|html?|feed|pdf|raw))$ [NC]# and the requested path and file doesn’t directly match a physical fileRewriteCond %{REQUEST_FILENAME} !-f# and the requested path and file doesn’t directly match a physical folderRewriteCond %{REQUEST_FILENAME} !-d# internally rewrite the request to the index.php scriptRewriteRule .* index.php [L]########### End — Joomla! core SEF Section

Bitrix 12

Options -IndexesErrorDocument 404 /404.php

<IfModule mod_php5.c>php_flag session.use_trans_sid off#php_value display_errors 1#php_value mbstring.internal_encoding UTF-8</IfModule>

<IfModule mod_rewrite.c>Options +FollowSymLinksRewriteEngine OnRewriteCond %{REQUEST_FILENAME} !-fRewriteCond %{REQUEST_FILENAME} !-lRewriteCond %{REQUEST_FILENAME} !-dRewriteCond %{REQUEST_FILENAME} !/bitrix/urlrewrite.php$RewriteRule ^(.*)$ /bitrix/urlrewrite.php [L]RewriteRule .* — [E=REMOTE_USER:%{HTTP:Authorization}]</IfModule>

<IfModule mod_dir.c>DirectoryIndex index.php index.html</IfModule>

<IfModule mod_expires.c>ExpiresActive onExpiresByType image/jpeg «access plus 3 day»ExpiresByType image/gif «access plus 3 day»ExpiresByType image/png «access plus 3 day»ExpiresByType text/css «access plus 3 day»ExpiresByType application/javascript «access plus 3 day»</IfModule>

Drupal 7

## Apache/PHP/Drupal settings:#

# Protect files and directories from prying eyes.<FilesMatch «\.(engine|inc|info|install|make|module|profile|test|po|sh|.*sql|theme|tpl(\.php)?|xtmpl)$|^(\..*|Entries.*|Repository|Root|Tag|Template)$»>Order allow,deny</FilesMatch>

# Don’t show directory listings for URLs which map to a directory.Options -Indexes

# Follow symbolic links in this directory.Options +FollowSymLinks

# Make Drupal handle any 404 errors.ErrorDocument 404 /index.php

# Set the default handler.DirectoryIndex index.php index.html index.htm

# Override PHP settings that cannot be changed at runtime. See# sites/default/default.settings.php and drupal_environment_initialize() in# includes/bootstrap.inc for settings that can be changed at runtime.

# PHP 5, Apache 1 and 2.<IfModule mod_php5.c>php_flag magic_quotes_gpc offphp_flag magic_quotes_sybase offphp_flag register_globals offphp_flag session.auto_start offphp_value mbstring.http_input passphp_value mbstring.http_output passphp_flag mbstring.encoding_translation off</IfModule>

# Requires mod_expires to be enabled.<IfModule mod_expires.c># Enable expirations.ExpiresActive On

# Cache all files for 2 weeks after access (A).ExpiresDefault A1209600

<FilesMatch \.php$># Do not allow PHP scripts to be cached unless they explicitly send cache# headers themselves. Otherwise all scripts would have to overwrite the# headers set by mod_expires if they want another caching behavior. This may# fail if an error occurs early in the bootstrap process, and it may cause# problems if a non-Drupal PHP file is installed in a subdirectory.ExpiresActive Off</FilesMatch></IfModule>

# Various rewrite rules.<IfModule mod_rewrite.c>RewriteEngine on

# Block access to «hidden» directories whose names begin with a period. This# includes directories used by version control systems such as Subversion or# Git to store control files. Files whose names begin with a period, as well# as the control files used by CVS, are protected by the FilesMatch directive# above.## NOTE: This only works when mod_rewrite is loaded. Without mod_rewrite, it is# not possible to block access to entire directories from .htaccess, because# <DirectoryMatch> is not allowed here.## If you do not have mod_rewrite installed, you should remove these# directories from your webroot or otherwise protect them from being# downloaded.RewriteRule «(^|/)\.» — [F]

# If your site can be accessed both with and without the ‘www.’ prefix, you# can use one of the following settings to redirect users to your preferred# URL, either WITH or WITHOUT the ‘www.’ prefix. Choose ONLY one option:## To redirect all users to access the site WITH the ‘www.’ prefix,# (http://example.com/… will be redirected to http://www.example.com/…)# uncomment the following:# RewriteCond %{HTTP_HOST} !^www\. [NC]# RewriteRule ^ http://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]## To redirect all users to access the site WITHOUT the ‘www.’ prefix,# (http://www.example.com/… will be redirected to http://example.com/…)# uncomment the following:# RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]# RewriteRule ^ http://%1%{REQUEST_URI} [L,R=301]

# Modify the RewriteBase if you are using Drupal in a subdirectory or in a# VirtualDocumentRoot and the rewrite rules are not working properly.# For example if your site is at http://example.com/drupal uncomment and# modify the following line:# RewriteBase /drupal## If your site is running in a VirtualDocumentRoot at http://example.com/,# uncomment the following line:# RewriteBase /

# Pass all requests not referring directly to files in the filesystem to# index.php. Clean URLs are handled in drupal_environment_initialize().RewriteCond %{REQUEST_FILENAME} !-fRewriteCond %{REQUEST_FILENAME} !-dRewriteCond %{REQUEST_URI} !=/favicon.icoRewriteRule ^ index.php [L]

# Rules to correctly serve gzip compressed CSS and JS files.# Requires both mod_rewrite and mod_headers to be enabled.<IfModule mod_headers.c># Serve gzip compressed CSS files if they exist and the client accepts gzip.RewriteCond %{HTTP:Accept-encoding} gzipRewriteCond %{REQUEST_FILENAME}\.gz -sRewriteRule ^(.*)\.css $1\.css\.gz [QSA]

# Serve gzip compressed JS files if they exist and the client accepts gzip.RewriteCond %{HTTP:Accept-encoding} gzipRewriteCond %{REQUEST_FILENAME}\.gz -sRewriteRule ^(.*)\.js $1\.js\.gz [QSA]

# Serve correct content types, and prevent mod_deflate double gzip.RewriteRule \.css\.gz$ — [T=text/css,E=no-gzip:1]RewriteRule \.js\.gz$ — [T=text/javascript,E=no-gzip:1]

<FilesMatch «(\.js\.gz|\.css\.gz)$»># Serve correct encoding type.Header set Content-Encoding gzip# Force proxies to cache gzipped & non-gzipped css/js files separately.Header append Vary Accept-Encoding</FilesMatch></IfModule></IfModule>

WordPress 3+

# BEGIN WordPress

<IfModule mod_rewrite.c>RewriteEngine OnRewriteBase /RewriteRule ^index\.php$ — [L]RewriteCond %{REQUEST_FILENAME} !-fRewriteCond %{REQUEST_FILENAME} !-dRewriteRule . /index.php [L]</IfModule>

# END WordPress

MOD X REVolution 2

# MODX supports Friendly URLs via this .htaccess file. You must serve web# pages via Apache with mod_rewrite to use this functionality, and you must# change the file name from ht.access to .htaccess.## Make sure RewriteBase points to the directory where you installed MODX.# E.g., «/modx» if your installation is in a «modx» subdirectory.## You may choose to make your URLs non-case-sensitive by adding a NC directive# to your rule: RewriteRule ^(.*)$ index.php?q=$1 [L,QSA,NC]

RewriteEngine OnRewriteBase /

# Rewrite www.domain.com -> domain.com — used with SEO Strict URLs plugin#RewriteCond %{HTTP_HOST} .#RewriteCond %{HTTP_HOST} !^example-domain-please-change\.com [NC]#RewriteRule (.*) http://example-domain-please-change.com/$1 [R=301,L]## or for the opposite domain.com -> www.domain.com use the following# DO NOT USE BOTH##RewriteCond %{HTTP_HOST} .#RewriteCond %{HTTP_HOST} !^www\.example-domain-please-change\.com [NC]#RewriteRule (.*) http://www.example-domain-please-change.com/$1 [R=301,L]

# Rewrite secure requests properly to prevent SSL cert warnings, e.g. prevent# https://www.domain.com when your cert only allows https://secure.domain.com#RewriteCond %{SERVER_PORT} !^443#RewriteRule (.*) https://example-domain-please-change.com/$1 [R=301,L]

# The Friendly URLs partRewriteCond %{REQUEST_FILENAME} !-fRewriteCond %{REQUEST_FILENAME} !-dRewriteRule ^(.*)$ index.php?q=$1 [L,QSA]

# Make sure .htc files are served with the proper MIME type, which is critical# for XP SP2. Un-comment if your host allows htaccess MIME type overrides.

#AddType text/x-component .htc

# If your server is not already configured as such, the following directive# should be uncommented in order to set PHP’s register_globals option to OFF.# This closes a major security hole that is abused by most XSS (cross-site# scripting) attacks. For more information: http://php.net/register_globals## To verify that this option has been set to OFF, open the Manager and choose# Reports -> System Info and then click the phpinfo() link. Do a Find on Page# for «register_globals». The Local Value should be OFF. If the Master Value# is OFF then you do not need this directive here.## IF REGISTER_GLOBALS DIRECTIVE CAUSES 500 INTERNAL SERVER ERRORS :## Your server does not allow PHP directives to be set via .htaccess. In that# case you must make this change in your php.ini file instead. If you are# using a commercial web host, contact the administrators for assistance in# doing this. Not all servers allow local php.ini files, and they should# include all PHP configurations (not just this one), or you will effectively# reset everything to PHP defaults. Consult www.php.net for more detailed# information about setting PHP directives.

#php_flag register_globals Off

# For servers that support output compression, you should pick up a bit of# speed by un-commenting the following lines.

#php_flag zlib.output_compression On#php_value zlib.output_compression_level 5

# The following directives stop screen flicker in IE on CSS rollovers. If# needed, un-comment the following rules. When they’re in place, you may have# to do a force-refresh in order to see changes in your designs.

#ExpiresActive On#ExpiresByType image/gif A2592000#ExpiresByType image/jpeg A2592000#ExpiresByType image/png A2592000#BrowserMatch «MSIE» brokenvary=1#BrowserMatch «Mozilla/4.[0-9]{2}» brokenvary=1#BrowserMatch «Opera» !brokenvary#SetEnvIf brokenvary 1 force-no-vary

NetCAt 5

DirectoryIndex index.php

AddDefaultCharset utf-8

# Если NetCat стоит в подпапке, например mysite, то# ErrorDocument 404 /mysite/netcat/require/e404.php# в противном случаеErrorDocument 404 /netcat/require/e404.php

Options -IndexesOptions +FollowSymLinks

<IfModule mod_php5.c>php_flag magic_quotes_gpc onphp_flag display_errors offphp_value error_reporting 0php_value arg_separator.output «&amp;»php_value mbstring.internal_encoding UTF-8php_value short_open_tag on

</IfModule>

<ifModule mod_rewrite.c>RewriteEngine OnRewriteCond %{REQUEST_FILENAME} !-fRewriteCond %{REQUEST_FILENAME} !-dRewriteCond %{REQUEST_FILENAME} !-l# Если NetCat стоит в подпапке, например mysite, то# RewriteRule ^(.+)$ /mysite/netcat/require/e404.php# в противном случаеRewriteRule ^(.+)$ /netcat/require/e404.phpRewriteRule .* — [E=HTTP_IF_MODIFIED_SINCE:%{HTTP:If-Modified-Since}]RewriteRule .* — [E=HTTP_IF_NONE_MATCH:%{HTTP:If-None-Match}]</ifModule>

CMS Simpla

AddDefaultCharset UTF-8ErrorDocument 404 /404ErrorDocument 401 /password.phpRewriteEngine on

RewriteRule    ^admin/?$  simpla [L]

RewriteRule ^catalog/([^/]+)/?$    index.php?module=ProductsView&category=$1 [L,QSA]RewriteRule ^catalog/([^/]+)/([^/]+)/?$    index.php?module=ProductsView&category=$1&brand=$2 [L,QSA]

RewriteRule ^products/([^/]+)/?$    index.php?module=ProductView&product_url=$1 [L,QSA]RewriteRule ^products/?$    index.php?module=ProductsView [L,QSA]

RewriteRule ^brands/([^/]+)/?$    index.php?module=ProductsView&brand=$1 [L,QSA]RewriteRule ^brands/([^/]+)/page_([^/]+)/?$    index.php?module=ProductsView&brand=$1&page=$2 [L,QSA]

RewriteRule ^search/([^/]+)/?$    index.php?module=ProductsView&keyword=$1 [L,QSA]RewriteRule ^search/?$    index.php?module=ProductsView [L,QSA]

RewriteRule ^blog/([^/]+)/?$    index.php?module=BlogView&url=$1 [L,QSA]RewriteRule ^blog/?$    index.php?module=BlogView [L,QSA]

RewriteRule ^cart/?$    index.php?module=CartView   [L,QSA]RewriteRule ^cart/([^/]+)/?$    index.php?module=CartView&add_variant=$1  [L,QSA]RewriteRule ^cart/remove/([^/]+)/?$    index.php?module=CartView&delete_variant=$1  [L,QSA]RewriteRule ^order/([^/]+)/?$    index.php?module=OrderView&url=$1  [L,QSA]RewriteRule ^order/?$    index.php?module=OrderView  [L,QSA]

RewriteRule ^user/login/?$    index.php?module=LoginView  [L,QSA]RewriteRule ^user/register/?$    index.php?module=RegisterView  [L,QSA]RewriteRule ^user/logout/?$    index.php?module=LoginView&action=logout  [L,QSA]RewriteRule ^user/password_remind/?$    index.php?module=LoginView&action=password_remind  [L,QSA]RewriteRule ^user/password_remind/([0-9a-z]+)/?$    index.php?module=LoginView&action=password_remind&code=$1  [L,QSA]RewriteRule ^user/?$    index.php?module=UserView  [L,QSA]

# Google sitemapRewriteRule ^sitemap.xml?$    sitemap.php  [L,QSA]

# XMLRewriteRule ^yandex.xml?$    yandex.php  [L,QSA]

# feedbackRewriteRule ^contact/?$    index.php?module=FeedbackView  [L,QSA]

#downloadsRewriteRule ^order/([^/]+)/([^/]+)/?$    index.php?module=OrderView&url=$1&file=$2  [L,QSA]

RewriteCond %{REQUEST_FILENAME} !-fRewriteCond %{REQUEST_FILENAME} !-dRewriteRule ^([^/]*)/?$    index.php?module=PageView&page_url=$1 [L,QSA]RewriteRule ^/?$    index.php?module=MainView&page_url= [L,QSA]

RewriteCond %{REQUEST_FILENAME} !-dRewriteCond %{REQUEST_FILENAME} !-fRewriteRule ^files/products/(.+) resize/resize.php?file=$1&token=%{QUERY_STRING}#RewriteCond %{THE_REQUEST} ^GET\ (.*)files/products/(.*)\?([A-z0-9]*)#RewriteRule ^files/products/(.+) resize/resize.php?file=%2&token=%3 [L,NE]

Вконтакте

Facebook

Twitter

Одноклассники

Мой мир

otdihalki.ru

Htaccess для Joomla, который работает

htaccess

Знаете ли вы, Вы можете значительно уменьшить размер и увеличить скорость загрузки вашего сайта, используя только .htaccess? Автоматическое сжатие ресурсов, ETags и другие прекрасные вещи часто упускаются из виду, хотя данные элементы могут значительно улучшить производительность вашего сайта. В этой статье мы попытаемся понятным языком объяснить, что это, что они делают, как использовать их на ваших собственных сайтах. Чтобы проиллюстрировать преимущества использования данных элементов, я провел несколько тестов с помощью двух очень популярных в свое время клубных (платных) шаблонов Joomla и стандартного шаблона Joomla (Atomic), и измерил результаты с помощью очень крутого инструмента от GTMetrix. Каждая из трех установок была произведена с установкой демо-данных поставщика. Было проведено несколько тестов, чтобы оценить преимущества использования htaccess для увеличения производительности сайта. Клубные шаблоны содержат значительно больше данных и изображений, чем базовый шаблон Joomla, поэтому и сравнение шаблона “Atomic” с коммерческими шаблонами - не сравнение "яблок с яблоками", однако результаты по-прежнему интересны.

  1. Показатель “BEFORE” - "До" теста, это контрольный показатель для оценки производительности "из коробки" и выполнены только две небольшие коррективы, для каждой демо-версии: переименование файла htaccess.txt Joomla в файл .htaccess и включена настройка перезаписи URL-адресов в глобальной конфигурации. Результаты в каждом результате довольно плохие.

  2. Показатель “AFTER” - "После" - результаты, которые показывают значительное снижение размера страницы, время загрузки и увеличение скорости загрузки сайта. Этот тест был проведен после замены стандартного файла .htaccess Joomla файл потяжелее, в прямом и переносном смысле. Исходный файл .htaccess весил 4КБ, а наш - 24 КБ с комментариями. При этом не было включено никаких расширений, плагинов, GZIP, кэширование и любых других видов сжатие. Результаты показывают увеличение скорости загрузки для шаблона Atomic на 46%, улучшение показателей для шаблона RT Voxel и YOO Stream на 34% и 25% соответственно.

  3. Тест "W/GZIP" был запущен после включения встроенного GZip-сжатия и кэширования в панели администратора, а также включения Кэша системы в менеджере плагинов. Однако никаких ощутимых изменений не произошло, чем я был весьма удивлен.

  4. Итоговый тест "JCH" - это показатель результата установки расширения JCH Optimize, который незначительно улучшили показатели клубных шаблонов, но значительно улучшил оценку показателя YSlow (показатель “A” означает оценку “Отлично”) для стандартного шаблона Joomla Atomic. Впечатляет!

Все тесты проводились на одном и том же виртуальном сервере с разницей в одну минуту между тестами.

Как это делается? Оставшаяся часть этой статьи становится немного сложнее. Вы должны прочитать все комментарии и выбрать решения для ваших конкретных потребностей.

Существует множество статей, говорящих о безопасности сайта и htaccess, а также о других расширениях, таких как Admin Tools от Akeeba Backup. Поэтому я не буду углубляться в подробности, связанные с безопасностью, а буду говорить, в основном, о производительности. В следующем коде много комментариев, объясняющих, что каждый элемент может сделать для вашего сайта. Основные особенности данного файла, которые ускорят ваш сайт - это теги ETag (тег объекта), Expires headers и автоматическое сжатие ресурсов.

  1. ETag говорит браузеру кэшировать изображения, которые он уже видел раньше, вместо того, чтобы загружать их заново, сообщая время и размер файла.

  2. Expires headers схож с ETag, но может иметь различные сроки кэширования для каждого типа файла. Мы сообщаем браузеру, что данный файл должен обновляться каждые столько-то дней/недель/месяцев.

  3. AddOutputFilterByType DEFLATE "уменьшает” исходный код вашего скомпилированного HTML файла, удалив ненужные переносы строк и пробелы. Шаблон YooTheme Steam сократился с 383 строк кода всего до 5!

КОД ФАЙЛА HTACCESS

########## Начало - ETag ## Это правло создаст ETag для файлов только на изменении ## времени и размера. Это работает особенно хорошо, если вы используете RSync## серверы, где номер inode идентичных файлов отличается.## Помните: Это может привести к проблемам с вашим сервером, и вам может потребовать удалить его.FileETag MTime Size########## Конец - ETag########## Начало - Автоматическое сжатие ресурсов# Сжатие текста, html, javascript, css, xml# Может закрыть доступ к вашему сайту через старые версии Internet Explorer# Сервер должен быть скомпилирован с mod_deflate в противном случае он будет посылать ошибку 500.# mod_deflate недоступен на Apache 1.x. Он может использоваться только с серверами Apache 2.x.# AddOutputFilterByType сейчас считается Apache устаревшим. В будущем придется использовать mod_filter.AddOutputFilterByType DEFLATE text/plain text/html text/xml text/css application/xml application/xhtml+xml application/rss+xml application/javascript application/x-javascript########## Начало - Оптимальное время истечения срока## Замечание: это может вызвать проблемы и вам придется закомментировать его

## с размещением хэша перед линиями этой секции # Enable expiration control ExpiresActive On # Default expiration: 1 hour after request ExpiresDefault "now plus 1 hour" # CSS and JS expiration: 1 week after request ExpiresByType text/css "now plus 1 week" ExpiresByType application/javascript "now plus 1 week" ExpiresByType application/x-javascript "now plus 1 week" # Image files expiration: 1 month after request ExpiresByType image/bmp "now plus 1 month" ExpiresByType image/gif "now plus 1 month" ExpiresByType image/jpeg "now plus 1 month" ExpiresByType image/jp2 "now plus 1 month" ExpiresByType image/pipeg "now plus 1 month" ExpiresByType image/png "now plus 1 month" ExpiresByType image/svg+xml "now plus 1 month" ExpiresByType image/tiff "now plus 1 month" ExpiresByType image/vnd.microsoft.icon "now plus 1 month" ExpiresByType image/x-icon "now plus 1 month" ExpiresByType image/ico "now plus 1 month" ExpiresByType image/icon "now plus 1 month" ExpiresByType text/ico "now plus 1 month" ExpiresByType application/ico "now plus 1 month" ExpiresByType image/vnd.wap.wbmp "now plus 1 month" ExpiresByType application/vnd.wap.wbxml "now plus 1 month" ExpiresByType application/smil "now plus 1 month" # Audio files expiration: 1 month after request ExpiresByType audio/basic "now plus 1 month" ExpiresByType audio/mid "now plus 1 month" ExpiresByType audio/midi "now plus 1 month" ExpiresByType audio/mpeg "now plus 1 month" ExpiresByType audio/x-aiff "now plus 1 month" ExpiresByType audio/x-mpegurl "now plus 1 month" ExpiresByType audio/x-pn-realaudio "now plus 1 month" ExpiresByType audio/x-wav "now plus 1 month" # Movie files expiration: 1 month after request ExpiresByType application/x-shockwave-flash "now plus 1 month" ExpiresByType x-world/x-vrml "now plus 1 month" ExpiresByType video/x-msvideo "now plus 1 month" ExpiresByType video/mpeg "now plus 1 month" ExpiresByType video/mp4 "now plus 1 month" ExpiresByType video/quicktime "now plus 1 month" ExpiresByType video/x-la-asf "now plus 1 month" ExpiresByType video/x-ms-asf "now plus 1 month" ########## Конец - Оптимальное время истечения срока

 

Советы и хитрости

Не все серверы одинаковы. Настройки сервера по умолчанию варьируются на каждом хостинге, а это означает, что некоторые параметры в файле .htaccess могут создать внутренную ошибку сервера 500. Лучший способ сузить поиск и выяснить реальную причину ошибки - это удалить кусок кода, загрузить, и снова проверить работоспособность сайта. Если ошибка сохраняется, замените первую часть и удалите другую, затем повторите шаги. Это очень удобно для того, чтобы записать номера строк, которые вы тестировали, чтобы найти причину ошибки.

Если вы поймете, чт CSS и javascript файлы работают неправильно - используйте специальные инструменты, такие как Firebug или инспектор элементов Chrome, чтобы увидеть логи ошибок. Ошибка 403 Forbidden, как правило означает, что вам заблокировали доступ к папке или типу файлов. Чтобы исправить ошибку, нужно искать путь к файлу ошибки и создать RewriteRule, чтобы разрешить доступ к этой папке, как в примерах ниже. На своем опыте я выяснил, что шаблонам RocketTheme нужен доступ к папке "fonts".  Шаблонам YooTheme и/или Widgetkit/Zoo нужен доступ в соответствующие папки кэша.

 

RewriteRule ^templates\/your_template_folder/ - [L]##Я выяснил, что это необходимо для @fontface fontsRewriteRule ^templates\/your_template_folder\/fonts/ - [L]##YooTheme Widgetkit и Zoo не будут правильно отображать изображения и css, если закрыть доступ к папке кэшаRewriteRule ^cache\/widgetkit/ - [L]RewriteRule ^cache\/com_zoo/ - [L]RewriteRule ^cache\/com_templates/ - [L]RewriteRule ^cache\/template/ - [L]RewriteRule ^cache\/plg_jch_optimize/ - [L]

 

Замечание

Это не исчерпывающее руководство, и оно не предназначено для того, чтобы быть сброшенным на ваш сайт Joomla в качестве замены стандартных файлов без предварительной настройки кода под ваш сайт и сервер. Требуется хорошее понимание кода файла .htaccess, иначе вы можете (временно) получить ошибку на своем сайте. Рекомендуем вам сначала протестировать ваш файл .htaccess на демо-сайте или демо-сервере, и помните, что всегда, абсолютно всегда нужно делать резервное копирование.

Ресурсы

 

СКАЧАТЬ

joomla.ru


Prostoy-Site | Все права защищены © 2018 | Карта сайта