使用 .htaccess 删除其他 php 页面上的 index.php 和文件扩展名

使用 .htaccess 删除其他 php 页面上的 index.php 和文件扩展名

我想消除在链接中包含 index.php 的需要。而不是

example.com/about/index.php

我希望如此

example.com/about/

其次,我还希望其他非索引页面可以在 URL 中不带 .php 文件扩展名的情况下进行导航。

example.com/about/who_we_are.php

我希望如此

example.com/about/who_we_are

我无法让两者同时工作。这是我的 .htaccess 文件中的内容:

Options -Indexes
DirectoryIndex index.php index.htm index.html
RewriteEngine On
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://example.com/$1 [L,R=301]
RewriteCond %{HTTP_HOST} ^www.example.com [NC]
RewriteRule ^(.*)$ https://example.com/$1 [L,R=301]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.php [NC,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]

目前,它正在从非索引页中删除 .php,但所有目录索引页都重定向到主页。

我究竟做错了什么?

答案1

发布这个问题后不久,我找到了解决这个问题的方法。

# remove .php; use THE_REQUEST to prevent infinite loops
RewriteCond %{HTTP_HOST} ^www\.example\.com
RewriteCond %{THE_REQUEST} ^GET\ (.*)\.php\ HTTP
RewriteRule (.*)\.php$ $1 [R=301]

# remove index
RewriteRule (.*)index$ $1 [R=301]

# remove slash if not directory
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} /$
RewriteRule (.*)/ $1 [R=301]

# add .php to access file, but don't redirect
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteCond %{REQUEST_URI} !/$
RewriteRule (.*) $1\.php [L]

我希望这可以帮助其他正在寻找此问题解决方案的人。

相关内容