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's a 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 Page Not Found або сторінка не може бути відображена помилка, як деякі веб-сервери лікувати посилання без Слеш як назва файлу замість каталогу, і, отже, не може знайти документи. 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 On
RewriteBase / RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f RewriteCond% (REQUEST_FILENAME)!-F
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)!-F
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 On
RewriteBase / RewriteBase /
RewriteRule ^([a-zA-Z0-9]+)/$ /$1 [L] RewriteRule ^ ([A-Za-Z0-9 ]+)/$ / $ 1 [L]
RewriteCond %{THE_REQUEST} ^[AZ]{3,9}\ /([a-zA-Z0-9]+) RewriteCond% (THE_REQUEST) ^ [AZ] (3,9) \ / ([A-Za-Z0-9] +)
RewriteRule ^([a-zA-Z0-9]+)$ /%1/? RewriteRule ^ ([A-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 Короткий пояснень від переписувати код для додавання косу риску в 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)!-F - Ця лінія включає всі 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] - цей процес без лінію слеш, який пройшов умовами, викладеними вище, шляхом додавання косу риску, а потім перенаправити з 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 Короткий пояснень для другого набору переписати правила і правила умови

RewriteRule ^([a-zA-Z0-9]+)/$ /$1 [L] – This line terminates the trailing slash appending rewrite process if the URL already contains trailing slash. RewriteRule ^ ([A-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) \ / ([A-Za-Z0-9] +) - Ця лінія визначає, що прохання не закінчується з слеш.

RewriteRule ^([a-zA-Z0-9]+)$ /%1/? RewriteRule ^ ([A-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] - Цей рядок додає слеш в кінці Урі і виконувати 301 постійних переадресацію на новий URL з слеш, а також припинити блоку перезапису.

IMPORTANT : The page is machine translated and provided "as is" without warranty. ВАЖЛИВО: Сторінка машина переведена і надаються "як є" без гарантії. Machine translation may be difficult to understand. Машинний переклад може бути важким для розуміння. Please refer to Будь ласка, зверніться до original English article оригінальний англійська статтю whenever possible. коли це можливо.


7 Responses to “Add Trailing Slash to the End of the URL with .htaccess Rewrite Rules” 7 Відповіді на "Додати косу риску в кінець URL с. Htaccess Переписати правила"

  1. Sushant Sushant
    September 1st, 2009 00:47 1 вересня 2009 00:47
    7 7

    Thanx. Thanx. Worked perfectly for me. Працював ідеально для мене. Even wordpress uses the same code in .htaccess. Навіть WordPress використовує той же самий код ст. Htaccess.

  2. any dog breed Будь-яка собака породи
    August 19th, 2009 07:07 19 серпня 2009 07:07
    6 6

    Couldn't get the second option to work for me either. Не вдалося отримати другий варіант, працювати на мене. Getting a 500 error. Початок помилку 500.

  3. an office equipment seller продавець оргтехніки
    January 19th, 2009 19:50 19 січня 2009 19:50
    5 5

    I'd been using that slash alot on one of my website. Я використовую, що коса риска багато в чому від одного з моїх веб-сайт. Most of them had been indexed by search engine successfully, but four of them return a 404 not found error based on Google Webmaster report, weird. Більшість з них були проіндексовані пошуковою системою успішно, але чотири з них повертаються 404 Not Found помилки на основі веб-майстрів Google доповідь, дивно.

  4. Nate Nate
    December 12th, 2008 12:53 12 грудня 2008 12:53
    4 4

    I have tried both methods and they do work but not with the other statement that I have. Я пробував обидва методу, і вони роблять роботу, але не з іншим твердженням, що в мене є. I was wondering exactly what Killswitch meant when he says “play with it a bit.” I tried rearranging the order and that doesn't seem to help, I'm looking for a quick solution here. Мені було цікаво саме те, що Killswitch в увазі, коли він говорить: "грати з ним трохи." Я намагався перебудови і тим, що не видається, щоб допомогти, я шукаю для швидкого вирішення тут.

  5. Killswitch Killswitch
    December 6th, 2008 10:37 6 грудня 2008 10:37
    3 3

    This was extremely helpful, I have been trying for the longest time to figure out how to end a site.com/somthing to site.com/something/ with no luck. Це було дуже корисно, я намагався протягом найбільш тривалого часу, щоб з'ясувати, як покласти край site.com / Somthing на site.com / Something / с не пощастило. Had to play with it a bit due to the rules I already have, but had it working in about 5 mins. Якщо б грати з ним трохи з-за правил, які я вже є, але вона працює в 5 хвилин.

  6. com COM
    October 31st, 2008 03:07 31 жовтня 2008 03:07
    2 2

    dlvrq rjdkq bfuwo jnlx dlvrq rjdkq bfuwo jnlx

  7. Na SEO muÅ¡ke - Vybrali.sme.sk a ukonÄ ujúce lomeno v URL | SEO chat На SEO MUA ¡Кошице - Vybrali.sme.sk ukonÄ Єврейська º CE lomeno в URL | SEO Chat
    July 26th, 2008 05:19 26 липня 2008 05:19
    1 1

    [...] Ä Ãm predÃdete aj problému Ä .2. [...] Ä Am predÃdete AJ problà © MU Ä .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 сом Naa ¡ІЕЛ Pěkná ½, ½ Але Anglická а-ля ¡NOK про те, як додавати слеш в кінці URL. Možnosti máte [...] МСХ ¾ nosti Mà ¡Te [...]

Leave a Reply Написати відповідь

You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> Ви можете використовувати ці теги: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <справі DateTime = ""> <em> <i> <q Cite=""> <strike> <strong>

Subscribe to comments feature has been disabled. Підписатися на коментарі функція була відключена. To receive notification of latest comments posted, subscribe to Щоб отримувати повідомлення про останні коментарях, підписатися My Digital Life Comments RSS feed Моя Цифрова життя Коментарі RSS Feed or або register to receive Увійдіть, щоб отримувати new comments in daily email digest. нові коментарі в щоденній електронній пошті.
Custom Search

New Articles Нові статті

Incoming Search Terms for the Article Вхідні терміни пошуку для статті

.htaccess append trailing slash . Htaccess додати слеш - -- mod rewrite add slash at the end Mod Rewrite додати слеш в кінці - -- rewriterule to add slash RewriteRule додати слеш - -- rewriterule trailing slash RewriteRule слеш - -- apache append trailing slash Apache додати слеш - -- apache add trailing slash Apache додати слеш - -- htaccess base url Htaccess URL база - -- add end slash Додати кінці слеш - -- google duplicate content url ending slash and not Google дублікат контента по URL, що закінчується косу риску і не - -- htaccess add slash Htaccess додати слеш - -- rewrite slash end слеш переписати кінець - -- htaccess add slash to end of directory Htaccess Додати косу риску в кінці каталогу - -- mod_rewrite add trailing slash mod_rewrite додати слеш - -- wordpress trailing slash WordPress слеш - -- htaccess trailing slash Htaccess слеш - -- remember add / slash seo Пам'ятайте Додати / Slash SEO - -- apache rewrite add trailing slash Apache переписати додати слеш - -- apache appending slashes Apache додаванням косою риси - -- apache rewrite to add traling slash Apache переписати, щоб додати трейлінг слеш - -- htaccess rewrite / end Htaccess переписати / кінець - -- htaccess end slash Htaccess кінці слеш - -- htaccess add to link Htaccess додати до посилання - -- htaccess url / end Htaccess URL / кінець - -- htaccess append slash on get Htaccess додати слеш, щоб отримати - -- rewrite htaccess without slash переписати Htaccess без слеш - -- rewrite rule add / правила перезапису додавати / - -- trailing slash end of url слеш в кінці URL - -- url trailing URL заднього - -- wordpress htaccess slash WordPress Htaccess слеш - -- .htaccess append .html at end of url . Htaccess додавання. HTML в кінці URL - -- add-url "Sex Toys" Add-URL "Секс іграшки" - -- add slash htaccess Додати слеш Htaccess - -- how to add end slash / in url Як додати кінці слеш / в URL - -- htaccess add trailing slash Htaccess додати слеш - -- htaccess with or without slash Htaccess з або без слеш - -- htaccess optional slash Htaccess необов'язкову косу риску - -- htaccess rewrite Htaccess переписати - -- mod rewrite remove trailing slash Mod Rewrite видалити косу риску - -- mod_rewrite base url mod_rewrite Базовий URL - -- mod_rewrite add slash mod_rewrite додати слеш - -- php add end slash PHP Наприкінці додати слеш - -- redirect trailing slash mod_rewrite перенаправити слеш mod_rewrite - -- request URI "ends with" htaccess URI запиту "закінчується" Htaccess - -- rewriterule slash problem RewriteRule проблема слеш - -- rewriterule complete URL with slash RewriteRule повний URL з косою риси - -- rewrite url ending перезапису URL, що закінчується - -- rewrite url apache add slash at end переписувати URL Apache додати слеш на кінці - -- rewriterule trainling slash redirect RewriteRule trainling слеш перенаправлення - -- trailing slash needed слеш необхідності - -- url ending slash URL, що закінчується слеш - --