大多数情况下,Web 开发人员不想在 URL 中显示文件扩展名。现在的问题是如何在不编写冗长程序或使用复杂方式的情况下从 URL 中隐藏或删除这些扩展名。
要从 URL 中删除扩展名,您可以使用 .htaccess
文件。这是从 URL 中删除扩展名的最简单方法。
请注意 .htaccess
不是文件扩展名。它只是 .htaccess 或 [dot]htaccess。
创建 a .htaccess
文件。转到您的项目根目录创建一个新文件并将其重命名为 .htaccess
。
.htaccess
必须在您的项目根目录中。要清除疑问,请参阅图像。
要在 URL 中隐藏 PHP 扩展,请将以下代码粘贴到您的 .htaccess
文件中。
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.php [NC,L]
要隐藏 URL 中的 HTML 扩展,请将以下代码粘贴到您的 .htaccess
文件中。
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.html [NC,L]
当您在 .htaccess
文件中添加 RewriteRule
后。然后从您的页面中删除 .php 或 .html 扩展名。
不添加 .htaccess
<html>
<body>
<a href="contact-us.php">Contact Us</a>
</body>
</html>
添加 .htaccess 后
<html>
<body>
<a href="contact-us">Contact Us</a>
</body>
</html>
在此处查看完整脚本。
RewriteEngine On
# remove the index file
RewriteCond %{THE_REQUEST} ^.*/index
RewriteRule ^(.*)index$ http://www.example.org/$1 [R=301,L]
# remove the .php extension
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(([^/]+/)*[^.]+)$ $1.php [L]
# redirect from .php to less php
RewriteCond %{THE_REQUEST} ^[A-Z]+\ /([^/]+/)*[^.#?\ ]+\.php([#?][^\ ]*)?\ HTTP/
RewriteRule ^(([^/]+/)*[^.]+)\.php http://www.example.org/$1 [R=301,L]
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://www.websparrow.org/misc/how-to-remove-php-html-extension-from-url-using-htaccess
内容来源于网络,如有侵权,请联系作者删除!