如何使用 htaccess 从 URL 中删除 php、html 扩展

x33g5p2x  于2021-10-21 转载在 PHP  
字(1.2k)|赞(0)|评价(0)|浏览(279)

大多数情况下,Web 开发人员不想在 URL 中显示文件扩展名。现在的问题是如何在不编写冗长程序或使用复杂方式的情况下从 URL 中隐藏或删除这些扩展名。

要从 URL 中删除扩展名,您可以使用 .htaccess 文件。这是从 URL 中删除扩展名的最简单方法。
请注意 .htaccess 不是文件扩展名。它只是 .htaccess[dot]htaccess

如何创建 .htaccess 文件?

创建 a .htaccess 文件。转到您的项目根目录创建一个新文件并将其重命名为 .htaccess

将 .htaccess 文件放在项目中的什么位置?

.htaccess 必须在您的项目根目录中。要清除疑问,请参阅图像。

隐藏 PHP 扩展

要在 URL 中隐藏 PHP 扩展,请将以下代码粘贴到您的 .htaccess 文件中。

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.php [NC,L]

隐藏 HTML 扩展

要隐藏 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]

相关文章