Add Trailing Slash to the End of the URL with .htaccess Rewrite Rules Добавьте косую черту в конце URL с. Htaccess Правила перезаписи
For a website that has URLs that end with a slash (/), it’sa good practice to ensure that all url links been parsed by the web server ended with trailing slash, even if visitors forget to enter the ending slash. На сайт с URL, что в конце косую черту (/), это хорошей практикой для обеспечения того, чтобы все ссылки были url разбираться в веб-сервере, закончившийся с косой чертой, даже если пользователи забудьте ввести заканчивающийся косой чертой. This avoid visitors been served with 404 Page Not Found or Page Cannot be Displayed error as some web servers treat links without trailing slash as a file name instead of directory, and thus unable to locate the documents. Это было избежать посетителей подается с 404 Страница не найдена или Страница не может быть показано, как некоторые ошибки веб-серверов, лечение без ссылки косую черту, как имя файла, вместо каталога, и, таким образом, удалось найти документы. It also eliminates the possibility that both pages with same content, one with slash at the end and another without, been viewed by search engines as duplicate content. Он также исключает возможность того, что обе страницы с одинаковым содержанием, одна с косой черты в конце, а другой без, рассматриваются поисковыми системами как дублированное содержание.
As an example, all hits to http://www.mydigitallife.info/contact should be redirect to http://www.mydigitallife.info/contact/. Как пример, все обращения к http://www.mydigitallife.info/contact следует перенаправлять на http://www.mydigitallife.info/contact/.
Most web server, including the popular Apache HTTPD web server supports mod_rewrite module where rules can be set in .htaccess file in order to redirect to add trailing slash to the URLs that does not already have one. Большинство веб-сервера, в том числе популярные Apache HTTPD веб-сервер поддерживает mod_rewrite модуля, где правила могут быть установлены в. Htaccess файл для перенаправления добавить косую черту для URL-адресов, которые уже не один.
The following code can be put in .htaccess to redirect URL without trailing slash to URL with trailing slash: Следующий код можно поместить в. Htaccess перенаправлять URL без косую черту в URL с косую черту:
RewriteEngine On Об RewriteEngine
RewriteBase / RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f RewriteCond% (REQUEST_FILENAME)!-Ж
RewriteCond %{REQUEST_URI} !index.php RewriteCond% (REQUEST_URI)! Index.php
RewriteCond %{REQUEST_URI} !(.*)/$ RewriteCond% (REQUEST_URI) !(.*)/$
RewriteRule ^(.*)$ http://domain.com/$1/ [L,R=301] RewriteRule ^(.*)$ http://domain.com/ $ 1 / [L, R = 301]
or или
RewriteCond %{REQUEST_FILENAME} !-f RewriteCond% (REQUEST_FILENAME)!-Ж
RewriteCond %{REQUEST_URI} !\..+$ RewriteCond% (REQUEST_URI)! \ .. + $
RewriteCond %{REQUEST_URI} !/$ RewriteCond% (REQUEST_URI)! / $
RewriteRule (.*) http://www.mydigitallife.info/$1/ [R=301,L] RewriteRule (.*) http://www.mydigitallife.info/ $ 1 [R = 301, L]
or или
RewriteEngine On Об RewriteEngine
RewriteBase / RewriteBase /
RewriteRule ^([a-zA-Z0-9]+)/$ /$1 [L] RewriteRule ^ ([-zA-Z0-9 ]+)/$ / $ 1 [L]
RewriteCond %{THE_REQUEST} ^[AZ]{3,9}\ /([a-zA-Z0-9]+) RewriteCond% () THE_REQUEST ^ [AZ] (3,9) \ / ([-zA-Z0-9] +)
RewriteRule ^([a-zA-Z0-9]+)$ /%1/? RewriteRule ^ ([-zA-Z0-9] +) $ / 1% /? [R=301,L] [R = 301, L]
In you’re using CMS or blog such as Wordpress that allows custom URL structure for permalinks, especially for search engine optimization (SEO), the above code should come before the block of rewrite conditions and rules for URL customization for the CMS or blog platform. В Вы используете CMS или блог например, Wordpress, который позволяет пользовательский URL на постоянные структуры, особенно для поисковой оптимизации (SEO), код должен быть представлен блок переписать условия и правила для URL для настройки CMS или блог платформы .
Brief explaination of the rewrite code to add trailing slash to URL Коротко о explaination переписывать код для добавления косую черту в URL
RewriteEngine On - This line enables the runtime rewriting engine based on mod_rewrite module of Apache. RewriteEngine On - Эта линия позволяет выполнения переписывающие движок на основе mod_rewrite модуля Apache.
RewriteBase / - This line sets the current page root directory as base URL for per-directory rewrites. RewriteBase / - Эта строка определяет текущую страницу корневого каталога в качестве базового URL для за-каталог перезаписи.
RewriteCond %{REQUEST_FILENAME} !-f - This line excludes all URLs pointing to existed files from been added with trailing slash again. RewriteCond% (REQUEST_FILENAME)!-Ж - Эта линия исключает все URL, указывающие на файлы из существовало были добавлены в косую черту снова. Directories cannot be excluded as this would exclude the rewrite behavior for existing directories. Каталоги не могут быть исключены, поскольку это исключило бы переписать поведение для существующих каталогов.
RewriteCond %{REQUEST_URI} !index.php - This line is optional, and will excludes a sample URL (in this case, index.php) that users do not want it to be rewritten. RewriteCond% (REQUEST_URI)! Index.php - Эта строка не является обязательным, и будет исключает выборки URL (в данном случае, index.php), что пользователи не хотят быть переписаны. Remove this line if not necessary. Удалить эту строку, если нет необходимости.
RewriteCond %{REQUEST_URI} !\..+$ - Specify that the URL does not contain any . RewriteCond% (REQUEST_URI)! \ .. + $ - Указать, что URL не содержит никаких. (dot) to exclude reference to file. (точка) исключить ссылку на файл.
RewriteCond %{REQUEST_URI} !(.*)/$ - This line determines which URL doesn’t contain a trailing slash RewriteCond% (REQUEST_URI) !(.*)/$ - Эта строка определяет, что URL не содержит косую черту
RewriteRule ^(.*)$ http://www.domain.com/$1/ [L,R=301] - This line process URL without trailing slash that has passed conditions set above, by appending a trailing slash and then redirect with 301 or permanent redirect status to the new URL. RewriteRule ^(.*)$ http://www.domain.com/ $ 1 / [L, R = 301] - Эта линия процесс URL без косую черту, который прошел условия, изложенные выше, путем добавления косую черту, а затем перенаправить с 301 или постоянную переадресацию статус новый URL. L mean this is the last line to process and the rewrite process can be terminated. L значит это последняя строка для обработки и перезаписи процесс может быть прекращен. Remember to replace the www.domain.com with your own domain name. Не забудьте заменить www.domain.com с вашим собственным доменным именем.
Brief explaination for second set of rewrite rules and rule conditions Краткие explaination для второго набора переписать правила и нормы условий
RewriteRule ^([a-zA-Z0-9]+)/$ /$1 [L] - This line terminates the trailing slash appending rewrite process if the URL already contains trailing slash. RewriteRule ^ ([-zA-Z0-9 ]+)/$ / $ 1 [L] - Эта линия прекращает косую черту дописывая переписывать процесс, если URL содержит косую черту.
RewriteCond %{THE_REQUEST} ^[AZ]{3,9}\ /([a-zA-Z0-9]+) - This line determines request that does not ends with trailing slash. RewriteCond% () THE_REQUEST ^ [AZ] (3,9) \ / ([-zA-Z0-9] +) - Эта строка определяет запрос, который не заканчивается на косую черту.
RewriteRule ^([a-zA-Z0-9]+)$ /%1/? RewriteRule ^ ([-zA-Z0-9] +) $ / 1% /? [R=301,L] - This line append a slash to the end of URI and perform a 301 permanent redirect to the new URL with trailing slash, and terminate the rewrite block. [R = 301, L] - Эта строка добавляет слэш к концу URI и выполнять 301 постоянную переадресацию на новый URL с косой чертой, и прекратить переписывать блок.
IMPORTANT : This is a machine translated page which is provided "as is" without warranty. ВАЖНО: Это машина переведена страница, на которой предоставляется "как есть" без гарантий. Machine translation may be difficult to understand. Машинный перевод может быть трудным для понимания. Please refer to Обратитесь к original English article Английский оригинал статьи whenever possible. когда это возможно.
Share and contribute or get technical support and help at Доля и вклад или получить техническую поддержку и помощь в My Digital Life Forums Моя Цифровая жизнь форумах .
Related Articles Статьи по теме
- Redirect or Rewrite to Remove Double or Multiple Slashes (//) in URL Перенаправить или перезаписи для устранения двойных или множественных косая черта (/ /) в URL
- SEO Friendly Rewrite Method to Move Website URL From Subdirectory to Root Parent Folder SEO дружественных переписать метод двигаться на сайте URL из подкаталога в корневой папке Родитель
- Remove and Uninstall or Disable ModSecurity (mod_security) Удалить и Удалить или отключить ModSecurity (mod_security)
- WordPress Permalinks Does Not Work in xampp Setup WordPress постоянные пока не работает в xampp Setup
- Remove or Trim First or Last Few Characters in MySQL Database with SQL Удалить или Trim Во-первых или последних нескольких символов в базу данных MySQL с SQL
- How to Move WordPress Blog to New Domain or Location Как перейти WordPress блог для нового домена или местоположения
- Fix Session Save Path Red Unwritable When Installing Joomla! Фикс сессии Сохранить путь Красного Unwritable при установке Joomla!
- How to Add a MySpace User As Friend in Friends List Как добавить пользователя, так как MySpace друга в список друзей
- How to Activate and Use FeedBurner MyBrand for Free Как активировать и использованию FeedBurner MyBrand даром
- Pulling the Wool Over the Boss’ Eyes Тянущие Шерсть За Boss глаза

































July 26th, 2008 05:19 26 июля 2008 05:19
[...] Ä Ãm predÃdete aj problému Ä .2. [...] Ä Ãm predÃdete ай problà © мю Ä .2. Pre htaccess som naÅ¡iel pekný, ale anglický Ä lánok o tom, how to add trailing slash to the end of the URL. Предварительное htaccess сом naÅ ¡iel peknà ½, ale anglickà ½ Ä là ¡nok о том, как добавить косую черту в конце URL. Možnosti máte [...] MoÅ ¾ nosti mà ¡тэ [...]