你应该已经链接到了你的内部URL上的文件without和.php
扩展名(即href="/page1"
,而不是href="/page1.php"
).我还假设您的URL不包含点(通常会分隔文件扩展名).
如果需要,执行重写以附加.php
扩展名.这需要接近根.htaccess
文件的顶部:
RewriteEngine On
# Internally rewrite extenionless URLs to append ".php" if required
# Tests only requests (that do not contain a dot) in the root directory
RewriteCond %{DOCUMENT_ROOT}/$1.php -f
RewriteRule ^([^./]+)$ $1.php [L]
RewriteCond
(文件系统判断)的替代方案:
RewriteCond %{REQUEST_FILENAME}.php -f
:
或者,您可以完全删除RewriteCond
指令,无条件地重写根目录中的所有请求(无文件扩展名)以附加.php
扩展名.
(可选)如果您正在更改URL struct ,并从URL中删除.php
个,并且旧URL已被搜索引擎索引和/或由第三方链接,那么您还需要实施重定向,以删除SEO的.php
扩展名.
在上述RewriteEngine
指令之后(内部重写之前)立即添加以下内容:
# Redirect to remove the `.php` extension inbound requests
# Only affects the root directory
RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteRule ^([^./]+)\.php$ /$1 [R=301,L]
针对REDIRECT_STATUS
环境变量进行测试的condition确保了我们不会在以后的重写中重定向已经重写的请求,从而避免了重定向循环.
注意:首先使用302(临时)重定向进行测试,以避免潜在的缓存问题.
或者(而不是#3),为了防止直接访问.php
文件并提供404 Not Found,请在上述RewriteEngine
指令之后立即添加以下内容(在内部重写之前):
# Prevent direct access to ".php" file and serve a 404 instead
# Only affects the root directory
RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteRule ^([^./]+)\.php$ - [R=404]
每次发生404错误时,显示自定义404页面内容的最佳方式是什么?(我不想使用重定向)
在.htaccess
文件的顶部使用以下命令,将完整的URL路径传递给ErrorDocument
指令.
ErrorDocument 404 /error-docs/e404.php
使用Sub的请求(称为"外部重定向"的文件没有内部错误).
请注意,这里应该包括.php
文件扩展名——这对用户来说是完全不可见的.