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. коли це можливо.
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 сайта Від підкаталог кореневій папці Батько
- Nintendo Plans on Price Slash for Wii to Compete Against Sony's PS3 and Microsoft's XBox Nintendo Плани за ціною Slash для Wii конкурувати з Sony PS3 і Xbox Microsoft's
- Microsoft Confirmed Price Slash on Xbox Consoles to Stay Competitively in Gaming Segment Microsoft підтверджена ціна Slash на консолі Xbox, щоб перебування в Конкурентоспроможна Gaming сегмента
- AUO Plans to Slash e-Book Pricing to $100 by 2011 AUO Плани Slash електронну книгу ціну до $ 100 до 2011 року
- D-Link Announced Price Slash on Entry Level 802.11n Wireless Router D-Link Оголошена ціна на Slash Entry Level бездротовий маршрутизатор 802.11n
- Remove or Trim First or Last Few Characters in MySQL Database with SQL Видаліть обрізки першого або останньої декілька символів в базі даних MySQL з SQL
- WordPress Permalinks Does Not Work in xampp Setup Постійні WordPress Чи не Робота в установці XAMPP
- PHP Scripts open_basedir Restriction in Effect Error PHP скрипти open_basedir Обмеження в Вплив помилку
- Unable to Logon to Win2003 Domain AD Due to Windows Cannot Connect to the Domain Error Не вдається ввійти до домену Win2003 AD З вікна не може підключитися до домену помилку










































September 1st, 2009 00:47 1 вересня 2009 00:47
Thanx. Thanx. Worked perfectly for me. Працював ідеально для мене. Even wordpress uses the same code in .htaccess. Навіть WordPress використовує той же самий код ст. Htaccess.
August 19th, 2009 07:07 19 серпня 2009 07:07
Couldn't get the second option to work for me either. Не вдалося отримати другий варіант, працювати на мене. Getting a 500 error. Початок помилку 500.
January 19th, 2009 19:50 19 січня 2009 19:50
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 доповідь, дивно.
December 12th, 2008 12:53 12 грудня 2008 12:53
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 в увазі, коли він говорить: "грати з ним трохи." Я намагався перебудови і тим, що не видається, щоб допомогти, я шукаю для швидкого вирішення тут.
December 6th, 2008 10:37 6 грудня 2008 10:37
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 хвилин.
October 31st, 2008 03:07 31 жовтня 2008 03:07
dlvrq rjdkq bfuwo jnlx dlvrq rjdkq bfuwo jnlx
July 26th, 2008 05:19 26 липня 2008 05:19
[...] Ä Ã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 [...]