使用 .htaccess 删除 .html 和 .php 扩展名
如何在不创建新目录和命名文件 index.php 的情况下从我的网页中删除文件类型.我希望 http://example.com/google.html http://example.com/google.
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.
我该怎么做.
PS:我尝试查看其他一些教程,但令人困惑.我现在可以在 .htaccess 中完成
PS: I tried looking at some other tutorials but there to confusing. I do now that it can be done in .htaccess
是的,我知道这个问题已经被问过多次并得到了回答,但我会根据我的经验给出更全面的答案.
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.
这里是 .htaccess 代码片段,可以帮助您:
Here is the .htaccess code snippet that will help you:
# Apache Rewrite Rules
<IfModule mod_rewrite.c>
Options +FollowSymLinks
RewriteEngine On
RewriteBase /
# Add trailing slash to url
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !(.[a-zA-Z0-9]{1,5}|/|#(.*))$
RewriteRule ^(.*)$ $1/ [R=301,L]
# Remove .php-extension from url
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^([^.]+)/$ $1.php
# End of Apache Rewrite Rules
</IfModule>
我想在这里强调一些重要的事情供大家参考:
I want to stress some important things here for everybody's reference:
- 此代码片段不会从 url 中删除入口脚本(例如
index.php
被许多 PHP 框架使用) - 它只删除
.php
扩展名,如果你想删除其他扩展名(例如.html
),复制粘贴第三块并替换php
带有其他扩展名. - 不要忘记从锚点(链接)href 中删除扩展名.
- 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 replacephp
with other extension. - Don't forget to also remove extension from anchors (links) href.