原来的答案实际上是正确的,但缺乏解释。我想补充一些解释和修改。
我建议阅读这篇简短的介绍https://httpd.apache.org/docs/2.4/rewrite/intro.html(15 分钟)并在阅读时参考这两页。
https://httpd.apache.org/docs/2.4/mod/mod_rewrite.html
https://httpd.apache.org/docs/2.4/rewrite/flags.html
这是从 URL 中隐藏 index.php 的基本规则。把它放在你的根 .htaccess 文件中。
mod_rewrite 必须使用 PHP 启用,这将适用于高于 5.2.6 的 PHP 版本。
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule (.*) /index.php/$1 [L]
将%{REQUEST_FILENAME} 视为主机之后的路径。
例如https://www.example.com/index.html, %{REQUEST_FILENAME} 是/index.html
所以最后 3 行的意思是,如果它不是常规文件 !-f 而不是目录 !-d,则执行 RewriteRule。
关于 RewriteRule 格式:
所以RewriteRule (.*) /index.php/$1 [L] 表示,如果满足 2 个RewriteCond,它(.*) 将匹配主机名之后的所有内容。 . 匹配任何单个字符,.* 匹配任何字符,(.*) 使这个变量可以用$1 引用,然后替换为/index.php/$1。最终效果是在整个 URL 路径中添加前面的index.php。
例如对于https://www.example.com/hello,它将产生https://www.example.com/index.php/hello 内部。
另一个关键问题是,这确实解决了问题。 内部,(我猜)它总是需要https://www.example.com/index.php/hello,但是通过重写,您可以在没有index.php 的情况下访问该站点,apache 在内部为您添加了这一点。
顺便说一句,Apache 文档不太推荐制作一个额外的 .htaccess 文件。
重写通常在主服务器配置中配置
设置(在任何<Directory> 部分之外)或在<VirtualHost> 内部
容器。这是最简单的重写方法,推荐