- Как сделать путь на сайте без раcширения (.html, .php)
- How to remove .php, .html, .htm extensions with .htaccess
- What is an .htaccess file
- Features
- Removing Extensions
- Adding a trailing slash at the end
- Conclusion
- Updates
- Remove .html and .php extensions with .htaccess
- 3 Answers 3
- Как убрать index.html из URL
- Как убрать index.html или index.php через .htaccess
Как сделать путь на сайте без раcширения (.html, .php)
Очень часто вижу что на сайтах после перехода на страницу нет расширения страницы в адресной строке. Например, ruSO Помощь, адрес выглядит именно https://ru.stackoverflow.com/help , а не https://ru.stackoverflow.com/help.php или https://ru.stackoverflow.com/help.html . Как именно это делается? И что это за технология? Плюс сразу же вопрос из той же оперы, но про api сайта. К примеру возьму Вконтакте. Вызов метода выглядит следующим образом:
https://api.vk.com/method/METHOD_NAME?PARAMETERS&access_token=ACCESS_TOKEN&v=V
То есть после METHOD_NAME нет .php , а на некоторых других сайтах есть. Плюс я еще встречал что-то вроде METHOD_NAME#. Что же это все означает и как реализовывается? И преимущества какие у каждого? UPD Сделал, получилось. Сервер apache Сделал следующим образом: index.php — в корне, остальные страницы в папке pages
Моя проблема с headers already sent by. решилась следующим образом. Я неправильно подошел к решению задачи, в файл index.php нужно лишь обрабатывать перенаправления, а я запихнул туда содержимое главной страницы.
В .htaccess написал в начале следующее:
RewriteEngine On RewriteBase / RewriteCond % !-f RewriteCond % !-d RewriteRule . /index.php [L]
case 'news': < include 'pages/news_page.php'; break; >case 'buy': < include 'pages/my_buy_page.php'; break; >case 'somepage': < include 'pages/somepage.php'; break; >> ?>
Интересно то, что папка includes находится на одном уровне с папкой pages , include в файле например pages/news_page.php нужно писать без ../ , то есть просто include (‘includes/foobar.php’); Все работает, спасибо @Stanislav, за подсказку
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:
RewriteEngine On RewriteCond % !-f RewriteRule ^([^\.]+)$ $1.php [NC,L]
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.
RewriteEngine On RewriteCond % !-f RewriteRule ^([^/]+)/$ $1.php RewriteRule ^([^/]+)/([^/]+)/$ /$1/$2.php RewriteCond % !-f RewriteCond % !-d RewriteCond % !(\.[a-zA-Z0-9]|/)$ RewriteRule (.*)$ /$1/ [R=301,L]
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:
Options +MultiViews RewriteEngine On RewriteCond % !-d RewriteCond % !-f RewriteRule ^([^\.]+)$ $1.php [NC,L]
If you’re worried that search engines might index these pages as duplicate content, add a meta tag in the of your HTML file:
Remove .html and .php extensions with .htaccess
How do I remove the file type from my webpages without creating a new directory and naming the file index.php. I want http://example.com/google.html to http://example.com/google. How would I go about doing this. PS: I tried looking at some other tutorials but there to confusing. I do now that it can be done in .htaccess
If you want to learn how to remove php and html extensions from URLs using htaccess , You can try this link helponnet.com/2020/02/04/…
3 Answers 3
Yes, I know that this question was asked multiple times already and is answered, but I will give a little more comprehensive answer based on my experience.
Here is the .htaccess code snippet that will help you:
# Apache Rewrite Rules Options +FollowSymLinks RewriteEngine On RewriteBase / # Add trailing slash to url RewriteCond % !-f RewriteCond % !(\.[a-zA-Z0-9]|/|#(.*))$ RewriteRule ^(.*)$ $1/ [R=301,L] # Remove .php-extension from url RewriteCond % !-d RewriteCond %\.php -f RewriteRule ^([^\.]+)/$ $1.php # End of Apache Rewrite Rules
I want to stress some important things here for everybody’s reference:
- This code snippet doesn’t remove entry scripts from url (such as index.php used by many PHP frameworks)
- It only removes .php extension, if you want to remove other extension as well (e.g. .html ), copy and paste 3rd block and replace php with other extension.
- Don’t forget to also remove extension from anchors (links) href.
@SimplePi Than I will suggest you accept the answer and mark it, so that this question doesn’t show up in unanswered ones. If you have any problems, let me know, so that I could help you further with this.
@armanP’s accepted answer above does not remove .php extension from php urls. It just makes it possible to access php files without using .php at the end. For example /file.php can be accessed using /file or /file.php but this way you have 2 diffrent urls pointing to the same location.
If you want to remove .php completely, you can use the following rules in /.htaccess :
RewriteEngine on #redirect /file.php to /file RewriteCond % \s/([^.]+)\.php [NC] RewriteRule ^ /%1 [NE,L,R] # now we will internally map /file to /file.php RewriteCond %.php -f RewriteRule ^(.*)/?$ /$1.php [L]
To remove .html ,use this
RewriteEngine on #redirect /file.html to /file RewriteCond % \s/([^.]+)\.html [NC] RewriteRule ^ /%1 [NE,L,R] # now we will internally map /file to/ file.html RewriteCond %.html -f RewriteRule ^(.*)/?$ /$1.html [L]
Solution for Apache 2.4* users :
If your apache version is 2.4 ,you can use the Code without RewriteConditions On Apache 2.4 we can use END flag instead of the RewriteCond to prevent Infinite loop error.
Here is a solution for Apache 2.4 users
RewriteEngine on #redirect /file.php to /file RewriteRule ^(.+).php$ /$1 [L,R] # now we will internally map /file to /file.php RewriteCond %.php -f RewriteRule ^(.*)/?$ /$1.php [END]
Note : If your external stylesheet or images aren’t loading after adding these rules ,to fix this you can either make your links absolute changing .Notice the / before the filename . or change the URI base add the following to head section of your Web page .
Your Webpage fails to load css and js due to the following reason :
When your browser url changes from /file.php to /file server thinks that /file is a directory and it tries to append that in front of all relative paths . For example : when your url is http://example.com/file/ your relative path changes to thus the image fails to load . You can use one of the solutions I mentioned in the last peragraph to solve this issue.
Как убрать 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, что делать?
RewriteEngine On RewriteRule ^index\.html$ / [R=301,L]
RewriteEngine On RewriteRule ^index\.php$ / [R=301,L]
Если у вас несколько файлов 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.php в разных папках, например, faq-reg.ru/support/index.php, вы можете применить правило:
RewriteEngine On RewriteRule ^index\.php$ / [R=301,L] RewriteRule ^(.*)/index\.php$ /$1/ [R=301,L]
Готово, после внесения правила в .htaccess ваш сайт будет открываться без index.html или index.php в конце URL.