如何将除某些 URL 之外的所有 URL 路由到 PHP 文件?

How to route all URLs except some to a PHP file?

我正在做一个 PHP 项目。我想将除某些(/、/index.php、/video-archive.php 等)之外的所有 URL 路由到一个 PHP 文件,即 /article.php

让我更详细地描述一下:

考虑到我在 URL https://example.com/article.php 有 article.php,当客户想要达到 URL https://example.com/how-to-grow-beautiful-flowers.php 或没有 .php 扩展名,我希望这个请求由这个 https://example.com/article.php URL 或简单的 article.php 文件处理。如果用户想要到达 https://example.com/https://example.com/index.phphttps://example.com/video-archive.php,他们将到达 index.phpvideo-archive.php。所以这条路线会有例外。

REQUEST URL                                            PROCESSING URL
https://example.com/                                   https://example.com/index.php
https://example.com/index.php                          https://example.com/index.php
https://example.com/index                              https://example.com/index.php
https://example.com/video-archive                      https://example.com/video-archive.php
https://example.com/video-archive.php                  https://example.com/video-archive.php
https://example.com/how-to-grow-flowers                https://example.com/article.php
https://example.com/types-of-flowers                   https://example.com/article.php
https://example.com/about-us                           https://example.com/article.php

注意:我目前正在我的计算机 (localhost) 上使用 XAMPP 开发这个项目。但我计划将来将其部署在服务器上。所以考虑一下这个信息应该会比较好。

您可以将所有请求重定向到 /article.php 除了对实际存在的文件的请求。对 /index.php/video-archive.php 和静态文件的示例请求将加载实际文件。试试这个

把这个放在根目录.htaccess

RewriteEngine On

# redirect all request to article.php except existing files
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^.*$ article.php [QSA,L]

然后您可以像这样在 article.php 文件中获取 URI

$article_url = rtrim(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH), '.php');
// when a client hits https://example.com/how-to-grow-beautiful-flowers.php
// $article_url equals '/how-to-grow-beautiful-flowers'