如何自动消除url中的文件名?
How to automatically eliminate the file name from the url?
我已经在使用 RewriteEngine 和 RewriteConditions 来删除文件名中的 .php 部分。
不过,我最近访问了这个网站,http://poorlydrawnlines.com/comic/tragedy/
。在里面,为了搞乱,我试着找到实际的文件名,结果是 index.php。但是,当我尝试转到 http://poorlydrawnlines.com/comic/tragedy/index.php
时,该站点会自动将 url 缩短为 http://poorlydrawnlines.com/comic/tragedy/
。这种行为是如何实现的?
此外,我假设页面的原始地址以 index.php 结尾是否正确?或者该网站只是在重定向我?我如何在我自己的网站中重新创建它?
您只需调整 RewriteCondition 以在请求的 URL 中查找 index.php 并将其删除,而不是仅删除 .php 扩展名。
已编辑举例:
RewriteEngine On
RewriteCond "%{REQUEST_URI}" "(.*)/index\.php"
RewriteRule ".*" "%1/" [R=301,L]
RewriteCond 用于捕获 folder/path 名称,然后 RewriteRule 在没有文件名的情况下重定向到它。这也会保留任何查询字符串参数。
由于您没有提供原始 .htaccess
代码,所以我只能这样做了。
RewriteCond %{THE_REQUEST} ^.*/index\.php
RewriteRule ^(.*)index.php$ / [R=301,L]
除了@cmorrissey 的回答,这个脚本也可以解决问题,没有 mod_rewrite
:
$lookup = 'index.php';
$parts = explode('?', $_SERVER['REQUEST_URI']);
if(substr($parts[0], -(strlen($lookup))) == $lookup){
header('location: ./');
die();
}
我已经在使用 RewriteEngine 和 RewriteConditions 来删除文件名中的 .php 部分。
不过,我最近访问了这个网站,http://poorlydrawnlines.com/comic/tragedy/
。在里面,为了搞乱,我试着找到实际的文件名,结果是 index.php。但是,当我尝试转到 http://poorlydrawnlines.com/comic/tragedy/index.php
时,该站点会自动将 url 缩短为 http://poorlydrawnlines.com/comic/tragedy/
。这种行为是如何实现的?
此外,我假设页面的原始地址以 index.php 结尾是否正确?或者该网站只是在重定向我?我如何在我自己的网站中重新创建它?
您只需调整 RewriteCondition 以在请求的 URL 中查找 index.php 并将其删除,而不是仅删除 .php 扩展名。
已编辑举例:
RewriteEngine On
RewriteCond "%{REQUEST_URI}" "(.*)/index\.php"
RewriteRule ".*" "%1/" [R=301,L]
RewriteCond 用于捕获 folder/path 名称,然后 RewriteRule 在没有文件名的情况下重定向到它。这也会保留任何查询字符串参数。
由于您没有提供原始 .htaccess
代码,所以我只能这样做了。
RewriteCond %{THE_REQUEST} ^.*/index\.php
RewriteRule ^(.*)index.php$ / [R=301,L]
除了@cmorrissey 的回答,这个脚本也可以解决问题,没有 mod_rewrite
:
$lookup = 'index.php';
$parts = explode('?', $_SERVER['REQUEST_URI']);
if(substr($parts[0], -(strlen($lookup))) == $lookup){
header('location: ./');
die();
}