Как убрать index.html из url?
Хвосты в виде .html убираются, но на главной странице всё ещё остаётся /index
Как должен выглядеть итоговый .htaccess файл, чтобы index.html тоже убирался?
- Вопрос задан более двух лет назад
- 89 просмотров
Комментировать
Решения вопроса 1
Dpy3b @Dpy3b Автор вопроса
RewriteEngine on
RewriteBase /
RewriteCond % ^[A-Z]\ /([^.]+)\.html\ HTTP
RewriteRule ^([^.]+)\.html$ /$1 [R=301,L]
RewriteCond % !(\.[^./]+)$
RewriteCond % !-d
RewriteCond % !-f
RewriteRule (.*) /$1.html
#///
RewriteEngine On
RewriteRule ^index\.html$ /$1 [R=301,L]
RewriteRule ^(.*)/index\.html$ /$1/ [R=301,L]
(сам ответил на свой вопрос, я молодец)
Ответ написан более двух лет назад
Можно попробовать всё это сделать компактнее
RewriteEngine on RewriteCond % ^$ RewriteRule ^(|.*?/)(?:index|([^/]*)\.html) /$1$2 [R=301,L] RewriteCond %/$1.html -f RewriteRule ^([^.]+)$ /$1.html [L]

Dpy3b @Dpy3b Автор вопроса
dodo512, Хм, действительно, работает. Спс чел!
Ответы на вопрос 0
Ваш ответ на вопрос
Войдите, чтобы написать ответ

- Обработка URL
Как сделать редиректы 301 всего сайта через htaccess?
- 1 подписчик
- 11 часов назад
- 18 просмотров
Как убрать index.html из URL
Предположим, вы заказали бесплатный хостинг для сайтов html в Рег.ру. По умолчанию когда вы открываете сайт в браузере, веб-сервер указывает в конце домена название индексного файла «index.html» или «index.php». Это негативно сказывается на поисковой позиции сайта. Для успешного продвижения в поисковых системах потребуется настройка переадресации с удалением «index.html» или «index.php» в конце адреса вашего сайта. Например, перенаправление с сайта «faq-reg.ru/index.html» на «faq-reg.ru»
Как убрать index.html или index.php через .htaccess
Откройте файл .htaccess в корневой директории сайта. Если у вас нет этого файла воспользуйтесь справкой: У меня нет файла .htaccess, что делать?
Добавьте в конце файла .htaccess одно из правил, которое подходит для вашего случая:
Как убрать index.html из URL для главной страницы
Чтобы убрать index.html в конце адреса вашего домена, воспользуйтесь правилом:
RewriteEngine On RewriteRule ^index\.html$ / [R=301,L]
Как убрать index.php из URL для главной страницы
Чтобы убрать index.php в конце адреса вашего домена, воспользуйтесь правилом:
RewriteEngine On RewriteRule ^index\.php$ / [R=301,L]
Как убрать index.html из URL для всех страниц
Если у вас несколько файлов index.html в разных папках, например, faq-reg.ru/support/index.html, вы можете убрать index.html из адресной строки, применив правило:
RewriteEngine On RewriteRule ^index\.html$ / [R=301,L] RewriteRule ^(.*)/index\.html$ /$1/ [R=301,L]
Теперь любой запрос, который оканчивается на «index.html», будет переадресован на URL без него.
Как убрать index.php из URL для всех страниц
Если у вас несколько файлов index.php в разных папках, например, faq-reg.ru/support/index.php, вы можете применить правило:
RewriteEngine On RewriteRule ^index\.php$ / [R=301,L] RewriteRule ^(.*)/index\.php$ /$1/ [R=301,L]
Теперь любой запрос, который оканчивается на «index.php», будет переадресован на URL без него.
Сохраните файл с внесенными изменениями.
Готово, после внесения правила в .htaccess ваш сайт будет открываться без index.html или index.php в конце URL.
Removing the index.html from url
Ok, maybe a pretty dumb question but I can’t find an answer on Google. I am coding my site by hand. How do I make the index.html disappear from the url’s? Do I use a piece of code in my html? Do I have to change my href’s in my files? Hope you guys can help! EDIT: I’ve tried this with a .htaccess file RewriteEngine On RewriteRule ^index\.html$ / [R=301,L] RewriteRule ^(.*)/index\.html$ /$1/ [R=301,L] It does work, but all my links aren’t working anymore. I discovered I had to remove all the index.html from the href’s in my documents. But that would be a lot of work. Is there an other code for .htaccess that just hides index.html?
David Hakkert
asked Mar 18, 2014 at 13:34
David Hakkert David Hakkert
669 3 3 gold badges 10 10 silver badges 25 25 bronze badges
You could redirect the user if location.href ends with index.html?
Mar 18, 2014 at 13:36
Mar 18, 2014 at 13:38
it is called mod rewrite and there is tons of stackoverflow question about it -> stackoverflow.com/search?q=mod+rewrite+index.html
Mar 18, 2014 at 13:38
@davidkonrad good resource, but if the user doesn’t know it’s called mod rewrite, they would never find these answers 🙂
Mar 18, 2014 at 13:57
@TylerH, yes you are right, sorry user1737979, no offense!!
Mar 18, 2014 at 14:15
8 Answers 8
A SIMPLE WAY TO DO THIS in Html:
(example in my case is a simple dual language site)
If your link looks like this:
You should change it to this:
If trying to link to another folder in your directory, like is my example:
You should change it to this:
Notice that «/» goes back to your root directory and automatically selects index.html, so that is why I used «en» for the English language site, because the name of the folder in that case is «en». You should also make sure that you have index.html in your English language folder, and not index-en.html.
answered Jan 29, 2015 at 18:16
Darko Atanasov Darko Atanasov
475 4 4 silver badges 4 4 bronze badges
Jul 17, 2017 at 15:15
This answer worked great for me. Thanks. For above comment on localhost, I don’t think it works when you’re testing locally. When I was testing in localhost, «/» displayed a list of files and folders contained in the project. But once I published the website, «/» worked just as intended.
Sep 2, 2019 at 11:39
Apache has .htaccess files and mod_rewrite, In your .htaccess file, set:
DirectoryIndex index.html
You can also set this up in the Apache site config files too
You can specify a list of filenames, so if it doesn’t find the first it moves to the next.
answered Mar 18, 2014 at 13:46
4,928 2 2 gold badges 23 23 silver badges 46 46 bronze badges
would be great if you wrote the extra 2 sets of lines as a complete example.
Feb 23, 2018 at 9:12
There are no extra lines for the .htaccess file. There are extra lines for the config files, which is why I provided links to them
Feb 25, 2018 at 13:11
mod_rewrite module is responsible for all the rewriteEngine. Check on your server whether is module is present and enable.
answered Mar 28, 2017 at 7:26
murtuza hussain murtuza hussain
458 1 1 gold badge 7 7 silver badges 18 18 bronze badges
You need to create a file called ‘.htaccess’ in the root directory of your site containing the following code:
RewriteEngine On RewriteCond % !-f RewriteRule ^([^\.]+)$ $1.html [NC,L]
And then make sure all the links on your site don’t contain ‘.html’ at the end, e.g.:
should be replaced with:
Hope this helps!
if you dont find .htaccess, you just need to create a new file using your text editor the same way you would any other html or css file, but save it as simply ‘.htaccess’
And save it into the root directory, so the same folder that you have your index.html file.
answered Mar 22, 2019 at 8:03
Ashish Yadav Ashish Yadav
133 1 1 silver badge 8 8 bronze badges
I think this is configured in IIS when you deploy the site, I’m not to sure on it but I’m sure you can specify a start point that your URL will use when you just enter the UL, that implies the Index.html page.
Sorry I’m not too helpful here, hopefully it will point you in the right direction.
Often these things such as Apache or IIS have this set up already, and it looks for the Index.html , Index.php first when you just put your URL in.
5,671 30 30 gold badges 44 44 silver badges 46 46 bronze badges
answered Mar 18, 2014 at 13:39
Joe Harper Joe Harper
470 2 2 silver badges 11 11 bronze badges
Great SEO idea! This is similar to nginx redirect loop, remove index.php from url and Apache .htaccess to hide both .php and .html extentions, as well as mod_rewrite not working htaccess — the idea here, for both Apache’s mod_rewrite and nginx ngx_http_rewrite, depends on the differences between the external and internal URLs — in order for the redirect from /index.html to / work, yet not cause redirect loops when actually serving index.html , you gotta make sure you only issue the redirect for external index.html requests, but never for internal ones; this can only be accomplished by looking into the actual request_uri .
Here’s the code for nginx ngx_mod_rewrite:
index index.html index.txt; if ($request_uri ~ "^(.*/)index\.(html|txt)$")
On Apache’s mod_rewrite, it’ll be something like the following:
RewriteEngine on RewriteCond % ^.*/index\.html$ RewriteRule ^(.*/)index.html$ $1 [R,L]
- nginx redirect loop, remove index.php from url
- Apache .htaccess to hide both .php and .html extentions
- mod_rewrite not working htaccess
- http://nginx.org/r/index
- http://nginx.org/r/if
- http://httpd.apache.org/docs/current/mod/mod_rewrite.html#RewriteCond
Как убрать index.html из URL
Файл index.html – это стандартный файл, который используется веб-серверами для отображения содержимого корневой директории сайта. Если вы открываете сайт без указания конкретного файла в URL, то веб-сервер автоматически открывает файл index.html, если он есть в корневой директории сайта.
Например, если у вас есть сайт с доменным именем example.com и файл index.html находится в корневой директории сайта, то вы можете открыть его, введя в адресной строке браузера следующий URL: http://example.com/index.html. Однако, если вы просто введете http://example.com, то веб-сервер автоматически откроет файл index.html.
Файл index.html может содержать HTML-код, который определяет структуру и содержимое веб-страницы. Он может также содержать ссылки на другие файлы, такие как CSS-стили, JavaScript-скрипты и изображения, которые используются на веб-странице.
В целом, использование файла index.html в URL позволяет упростить адрес сайта и обеспечить быстрый доступ к содержимому корневой директории сайта, однако это негативно сказывается на поисковой позиции сайта. Чтобы успешно продвигать его поисковых системах нужно настроить переадресацию с удалением «index.html» в конце адреса сайта. Например, перенаправление с сайта «example.com/index.html» на «example.com».
Как убрать index.html через htaccess
Чтобы убрать index.html из URL сайта, можно использовать файл .htaccess. Для этого нужно выполнить следующие шаги:
- Создайте файл .htaccess в корневой директории сайта, если его еще нет.
- Добавьте в файл правило – в зависимости от того, что вам нужно:
Убрать index.html из URL для главной страницы:
RewriteRule ^index\.html$ / [R=301,L]
Убрать index.html из URL для всех страниц:
RewriteRule ^index\.html$ / [R=301,L]
RewriteRule ^(.*)/index\.html$ /$1/ [R=301,L]
- Сохраните изменения.
Как убрать index.php через web.config
Если говорить в общем, web.config позволяет веб-разработчикам изменять настройки приложений без необходимости изменения кода приложений. Каждое веб-приложение имеет свой web.config, который хранится в корневой папке приложения на сервере.
Чтобы убрать index.html из URL сайта через web.config нужно выполнить следующие шаги:
- Войдите в панель управления хостингом и перейдите в корневую директорию сайта.
- Выберите файл web.config.
- Добавьте в файл следующие правила:
Чтобы подготовить страницу к редиректу:
