Как убрать html в конце url
Перейти к содержимому

Как убрать html в конце url

  • автор:

Убрать расширение .html в конце адреса

Для того, что бы убрать расширение файла в конце адреса в браузере, вам нужно отредактировать файл .htaccess, который находится в корневой директории вашего сайта. Если такого файла нет — создайте его.

Найдите в файле строчку, содержащую:

Сразу после этой строчки вставьте следующие правила.
Если нужно убрать .php:

Если необходимо убрать .html:

Если вам необходимо убрать .htm:

Если строчка «RewriteEngine On» отсутствует в файле – добавьте ее в самое начало. После чего сохраните изменения.

Если раньше адреса на вашем сайте были вида:

то теперь вы можете открыть эту страницу по адресу:

Похожие статьи

Скачать базу данных MySQL?
DNS ещё не обновился. Как получить доступ к сайту?
Как перенести сайт на Hosty.by

Добавить комментарий Отменить ответ

Для отправки комментария вам необходимо авторизоваться.

Этот сайт использует Akismet для борьбы со спамом. Узнайте, как обрабатываются ваши данные комментариев.

How to remove .html from URL?

Also, I need to redirect any url with .html to the one without it. (i.e. www.example.com/page.html to www.example.com/page ).

18 Answers 18

I think some explanation of Jon’s answer would be constructive. The following:

checks that if the specified file or directory respectively doesn’t exist, then the rewrite rule proceeds:

But what does that mean? It uses regex (regular expressions). Here is a little something I made earlier. enter image description here

I think that’s correct.

NOTE: When testing your .htaccess do not use 301 redirects. Use 302 until finished testing, as the browser will cache 301s. See https://stackoverflow.com/a/9204355/3217306

Update: I was slightly mistaken, . matches all characters except newlines, so includes whitespace. Also, here is a helpful regex cheat sheet

binaryfunt's user avatar

To remove the .html extension from your urls, you can use the following code in root/htaccess :

NOTE: If you want to remove any other extension, for example to remove the .php extension, just replace the html everywhere with php in the code above.

Amit Verma's user avatar

This should work for you:

With .htaccess under apache you can do the redirect like this:

As for removing of .html from the url, simply link to the page without .html

You will need to make sure you have Options -MultiViews as well.

None of the above worked for me on a standard cPanel host.

For those who are using Firebase hosting none of the answers will work on this page. Because you can’t use .htaccess in Firebase hosting. You will have to configure the firebase.json file. Just add the line «cleanUrls»: true in your file and save it. That’s it.

After adding the line firebase.json will look like this :

Harsh Prajapati's user avatar

Thanks for your replies. I have already solved my problem. Suppose I have my pages under http://www.yoursite.com/html, the following .htaccess rules apply.

Rince Thomas's user avatar

Good question, but it seems to have confused people. The answers are almost equally divided between those who thought Dave (the OP) was saving his HTML pages without the .html extension, and those who thought he was saving them as normal (with .html ), but wanting the URL to show up without. While the question could have been worded a little better, I think it’s clear what he meant. If he was saving pages without .html , his two question (‘how to remove .html’) and (how to ‘redirect any url with .html’) would be exactly the same question! So that interpretation doesn’t make much sense. Also, his first comment (about avoiding an infinite loop) and his own answer seem to confirm this.

So let’s start by rephrasing the question and breaking down the task. We want to accomplish two things:

  1. Visibly remove the .html if it’s part of the requested URL (e.g. /page.html )
  2. Point the cropped URL (e.g. /page ) back to the actual file ( /page.html ).

There’s nothing difficult about doing either of these things. (We could achieve the second one simply by enabling MultiViews.) The challenge here is doing them both without creating an infinite loop.

Dave’s own answer got the job done, but it’s pretty convoluted and not at all portable. (Sorry Dave.) Łukasz Habrzyk seems to have cleaned up Anmol’s answer, and finally Amit Verma improved on them both. However, none of them explained how their solutions solved the fundamental problem—how to avoid an infinite loop. As I understand it, they work because THE_REQUEST variable holds the original request from the browser. As such, the condition ( RewriteCond % ) only gets triggered once. Since it doesn’t get triggered upon a rewrite, you avoid the infinite loop scenario. But then you’re dealing with the full HTTP request— GET , HTTP and all—which partly explains some of the uglier regex examples on this page.

I’m going to offer one more approach, which I think is easier to understand. I hope this helps future readers understand the code they’re using, rather than just copying and pasting code they barely understand and hoping for the best.

Let’s break it down…

The first rule is pretty simple. The condition matches any URL ending in .html (or .htm ) and redirects to the URL without the filename extension. It’s a permanent redirect to indicate that the cropped URL is the canonical one.

The second rule is simple too. The first condition will only pass if the requested filename is not a valid directory ( !-d ). The second will only pass if the filename refers to a valid file ( -f ) with the .html extension added. If both conditions pass, the rewrite rule simply adds ‘.html’ to the filename. And then the magic happens… [END] . Yep, that’s all it takes to prevent an infinite loop. The Apache RewriteRule Flags documentation explains it:

Using the [END] flag terminates not only the current round of rewrite processing (like [L]) but also prevents any subsequent rewrite processing from occurring in per-directory (htaccess) context.

Как правильно убрать .html в конце URL? Способ для HTML сайтов и Mobirise.

удаление .html расширения на конце страницы сайта

Поэтому, владельцы HTML сайтов, часто задаются вопросом ,а как убрать .html в конце адреса каждой веб-страницы?

Если у вас HTML сайт, или сайт на конструкторе сайтов Mobirise, вам нужно создать файл .htaccess и разместить его в корень вашего сайта на хостинге. Создать файл .htaccess, можно в любом текстовом редакторе. Однако, лучше это сделать в программе Notepad++ или аналогичной.

1-й Вариант файла .htaccess — самый оптимальный вариант.

Способ для HTML сайтов. В том числе и для тех сайтов, которые созданы в конструкторе сайтов Mobirise.

Файл .htaccess, должен содержать следующую информацию:

RewriteCond % ^[A-Z]<3,9>\ /index\.html\ HTTP/
RewriteRule ^index\.html$ https://ВАШ_САЙТ/ [R=301,L]

Redirect 301 /index https://ВАШ_САЙТ

Где указанно ВАШ_САЙТ, необходимо указать URL вашего сайта. Если код не заработает, вставьте в самом начале следующую строку:

Файл .htaccess, нужно сохранить со следующим именем:

При этом, он должен быть без расширения. Сохраняйте его, БЕЗ расширения на конце файла! Если файл сохранился у вас с расширением (часто, это расширение .txt), выберите Переименовать файл и удалите расширение (при условии, если у вас в системе, настроено отображение расширений на конце файлов). При сообщении системы о том, что фал может перестать работать, Соглашаемся и подтверждаем действие. Вот скрин, как должен выглядеть сохраненный файл:

имя файла .htaccess

Данный код, что приведен выше, позволит вам не только убрать .html на конце страниц, а и удалить дубль главной страницы index.html, благодаря 301 редиректу, на ваш основной домен сайта. Также, у вас должен быть подключен на сайте SSL сертификат безопасности, так ка этот код, расчитан на сайты, которые работают по https:// протоколу.

2-й Вариант файла .htaccess — не на всех хостингах работает.

Используйте данный способ, если 1-й Вариант, у вас не работает.

Удаление .html в адресе страниц на сайте, созданном в Mobirise.
Создайте текстовый файл и назовите его .htaccess
Введите в него этот текст, сохраните его и загрузите в папку сайта на сервере.

Код файла .htaccess:

3-й Вариант файла .htaccess — если не работает 2-й вариант.

Используйте данный способ, если 2-й Вариант, у вас не работает.

Аналогичный код со второго варианта, только удаляем строку:

При этом, 2-й и 3-й варианты, не удаляют дубль на главную страницу. При желании, вы можете добавить 301 редирект, в конце содержимого кода (через пробел на одну строку в конце основного кода, по аналогу с первым вариантом):

Где вместо ВАШ_САЙТ, указываем URL на свою главную страницу. Если не настроить 301 редирект, ваша главная страница сайта, будет открываться приблизительно так:

mobirise убрать html из url

исправление дублей страниц на сайте

На заметку.

Если у вас сайт на Mobirise, есть инструкция на официальном сайте Mobirise с информацией, как убрать .html на конце страницы. В принципе, если вышеприведенные варианты не сработают, воспользуйтесь данным способом, как последним вариантом.

Обратите внимание!

Уже неоднократно сталкиваюсь, когда пользователи создают данный файл (файл .htaccess), с расширением на конце. Нередко, встречаю .txt на конце. Вот пример неверного файла:

файл .htaccess с ошибкой

Это — ОШИБКА. На конце файла, НЕ должно быть расширения. Только, название .htaccess

На хостинге, файл .htaccess, будет выглядеть так:

правильный .htaccess

Файлы .htaccess в данной заметке, применимы для всех HTML сайтов, в том числе и для сайтов, созданных в конструкторе Mobirise, что позволяет убрать html из url страниц. Способ рабочий и используется мною на всех сайтах HTML. Однако, при создании файла .htaccess, нет универсальных решений. Некоторые хостинги, не дают доступ к редактированию/созданию файла .htaccess и/или вносят ряд ограничений. При этом, в большинстве случаев, приведенные выше варианты, самые оптимальные и универсальные.

Нужен стабильный, безопасный и недорогой хостинг?

Безопасный, стабильный и доступный по цене хостинг. Узнать больше.

Добавлено 22.02.2021

По просьбе пользователя в комментарии, добавляю вариант для тех, кому нужно убрать полностью index.html на всех страницах сайта. Используйте следующий код:

На некоторых хостингах, нужно добавлять в самом начале:

Должно быть так:

И вот код, для первого варианта:

RewriteCond % ^[A-Z]<3,9>\ /index\.html\ HTTP/
RewriteRule ^index\.html$ https://www.ВАШ_САЙТ/ [R=301,L]

RewriteRule ^index\.html$ / [R=301,L]
RewriteRule ^(.*)/index\.html$ /$1/ [R=301,L]

Повторюсь, что настройки .htaccess, сильно зависят от каждого хостинга. Если у вас возникают проблемы с настройкой .htaccess на вашем хостинге, обратитесь за помощью к техподдержке своего хостинга.

Если будут вопросы, поправки и дополнения – оставляйте комментарии.

How to remove .php, .html, .htm extensions with .htaccess

I recently wanted to remove the extensions from my website, in order to make the URLs more user and search engine friendly. I stumbled across tutorials on how to remove the .php extension from a PHP page. What about the .html ? I wanted to remove those as well! In this tutorial I’ll show you how to do that easily, by editing the .htaccess file.

What is an .htaccess file

An .htaccess file is a simple ASCII file that you create with a text editor like Notepad or TextEdit. The file lets the server know what configuration changes to make on a per-directory basis.

Please note that .htaccess is the full name of the file. It isn’t file.htaccess , it’s simply .htaccess .

.htaccess files affect the directory in which they are placed in and all children (sub-directories). For example if there is one .htaccess file located in your root directory of yoursite.com , it would affect yoursite.com/content/ , yoursite.com/content/images/ , and so on…

It is important to remember that this can be bypassed. If you don’t want certain .htaccess commands to affect a specific directory, place a new .htaccess file within the directory you don’t want to be affected with the changes, and remove the specific command(s) from the new file.

Features

With an .htaccess file you can:

  • Redirect the user to different page
  • Password protect a specific directory
  • Block users by IP
  • Preventing hot-linking of your images
  • Rewrite URLs
  • Specify your own Error Documents

In this tutorial we’ll be focusing only on rewriting URLs.

Removing Extensions

To remove the .php extension from a PHP file for example yoursite.com/wallpaper.php to yoursite.com/wallpaper you have to add the following code inside the .htaccess file:

If you want to remove the .html extension from a html file for example yoursite.com/wallpaper.html to yoursite.com/wallpaper you simply have to change the last line from the code above, to match the filename:

That’s it! You can now link pages inside the HTML document without needing to add the extension of the page. For example:

Adding a trailing slash at the end

I received many requests asking how to add a trailing slash at the end, for example: yoursite.com/page/

Ignore the first snippet and insert the code below. The first four lines deal with the removal of the extension and the following, with the addition of the trailing slash and redirecting.

Link to the HTML or PHP file the same way as shown above. Don’t forget to change the code if you want it applied to an HTML file instead of PHP.

Some people asked how you can remove the extension from both HTML and PHP files. I don’t have a solution for that. But, you could just change the extension of your HTML file from .html or .htm to .php and add the code for removing the .php extension.

Conclusion

For those who are not so experienced with .htaccess files there is an online tool for creating them. It’s useful for novice users to get started, and easy to use.

Updates

Attention GoDaddy users: In order to remove the extensions you need to enable MultiViews before. The code should look like this:

If you’re worried that search engines might index these pages as duplicate content, add a <canonical> meta tag in the <head> of your HTML file:

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *