如何修改 .htaccess 文件以避免拥有同一个 index.php 文件的多个副本?

How can I modify the .htaccess file so that I avoid having multiple copies of the same index.php file?

我正在开发一个电子学习网站,平台上每门课程都有一个课程预览页面。平台的文件结构类似于 https://example.com/courses/[course_id...]/index.php,PHP 代码从父目录名称中获取课程 ID,以便在数据库中查找。这里的问题是我必须在我创建的每个课程目录中制作相同的 index.php 文件副本,所以有没有办法以我只能有一个的方式修改 .htaccess 文件index.php 文件的副本?

假设您有一个名为 course.php 的文件。该文件根据 URL 处的 ID 提取课程,例如: http:///localhost/course.php?id=1

在你的.htaccess

RewriteEngine on
RewriteRule ^courses/([0-9]+)$ course.php?id=

然后可以到http:///localhost/courses/1获取课程ID 1。

https://httpd.apache.org/docs/2.4/rewrite/intro.html

  1. 创建 index.php 根
<?php
#For security course must exist.
# -1 will display 404
$course  = isset($_GET['course']) ? $_GET['course'] : -1;
$courses = [
    '1', '2', '3',
];
if (!in_array($course, $courses)){
    header("HTTP/1.0 404 Not Found");
    echo '404';
    exit();
}

include_once("courses/".$course."/course.php");
  1. 创建 root 的 .htaccess
RewriteEngine On
# course/x to /index.php?course=x
RewriteRule ^course/([0-9]+) /index.php?course= [QSA,L]
# protect folder courses
RewriteRule ^courses/(.+)$ - [F,L]
  1. 您的目录将如下所示。
root/
    index.php
    .htaccess
    /courses
            /1
              /course.php
            /2
              /course.php
Goto http://app.local/course/1 to /courses/1/course.php