@armanP 上面接受的答案不是来自 php url 的 remove .php 扩展名。它只是使访问 php 文件成为可能,而无需在最后使用.php。例如/file.php 可以使用/file 或/file.php 访问,但这样你就有2 个不同的url 指向同一个位置。
如果要彻底删除.php,可以在/.htaccess中使用以下规则:
RewriteEngine on
#redirect /file.php to /file
RewriteCond %{THE_REQUEST} \s/([^.]+)\.php [NC]
RewriteRule ^ /%1 [NE,L,R]
# now we will internally map /file to /file.php
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.*)/?$ /$1.php [L]
要删除 .html,请使用此
RewriteEngine on
#redirect /file.html to /file
RewriteCond %{THE_REQUEST} \s/([^.]+)\.html [NC]
RewriteRule ^ /%1 [NE,L,R]
# now we will internally map /file to/ file.html
RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule ^(.*)/?$ /$1.html [L]
Apache 2.4* 用户解决方案:
如果您的 apache 版本是 2.4,您可以使用不带 RewriteConditions 的代码在 Apache 2.4 上,我们可以使用 END 标志而不是 RewriteCond 来防止无限循环错误。
这是 Apache 2.4 用户的解决方案
RewriteEngine on
#redirect /file.php to /file
RewriteRule ^(.+).php$ /$1 [L,R]
# now we will internally map /file to /file.php
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.*)/?$ /$1.php [END]
注意:如果您的外部样式表或图像
添加这些规则后未加载,要解决此问题,您可以将链接绝对更改为 <img src="foo.png> 至 <img src="/foo.png>。注意文件名前的 /。或更改 URI 基础,将以下内容添加到网页的 head 部分 <base href="/"> 。
由于以下原因,您的网页无法加载 css 和 js:
当您的浏览器 url 从 /file.php 更改为 /file 时,服务器认为 /file 是一个目录,并尝试将其附加到所有相对路径的前面。例如:当您的 url 是 http://example.com/file/ 您的相对路径更改为 <img src "/file/foo.png"> 因此图像无法加载。您可以使用我在上一段中提到的解决方案之一来解决此问题。