如何使用 htaccess 删除 index.php

How to remove index.php using htaccess

我目前正在构建一个基于 PHP 的投资组合网站,没有任何框架。我在根目录和许多文件夹中创建了一个 index.php 文件,即 /about/contact/portfolio 等。在每一个中,我都有一个单独的 index.php 文件

我创建了一个 .htaccess 文件,在其中,我有这段代码...

Options +FollowSymLinks
Options -Indexes
DirectoryIndex index.php
RewriteEngine on
RewriteCond  !^(index\.php|images|robots\.txt)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/ [L,QSA]

由于某些原因,当我在 example.com/index.phpexample.com/about/index.php 访问我的网站时,.htaccess 文件无法正常工作并删除它。

知道为什么吗?

RewriteCond  !^(index\.php|images|robots\.txt)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/ [L,QSA]

如果这些指令的目的是从请求的 URL 中 删除 index.php,那么您使用了错误的规则!如果 /something 不映射到文件或目录。

您可能已经构建了 URL,因此它们映射到提供 DirectoryIndex 的文件系统目录,因此上述指令似乎完全多余。 (?)


从任何 URL

的末尾删除 index.php

要从任何 URL 中删除 index.phpDirectoryIndex),您需要改为执行以下操作:

RewriteRule ^(.+/)?index\.php$ / [R=301,L]

首先使用 302(临时)重定向进行测试,以避免潜在的缓存问题。

澄清...

  • 您不能在内部链接到 /index.php/about/index.php。以上指令仅适用于用户或外部站点错误地直接请求 index.php 文件。

  • 并在您的内部链接中包含尾部斜杠。例如。您应该在内部链接到 /about//contact/ 等(而不是 /about/contact),否则 mod_dir 将隐式发出 301 重定向以附加尾随斜杠。

花了一些时间,感谢怀特先生的建议,这是我的解决方案..

Options +FollowSymLinks -MultiViews
# Turn mod_rewrite on
RewriteEngine On
RewriteBase /

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php? [L,QSA]

RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s(.*)/index\.php [NC]
RewriteRule ^ %1 [R=301,L]

现在完美运行。 感谢所有抽出时间帮助我的人。