在PHP中使用.htaccess和Apache进行路由时会遇到“未找到”问题

o7jaxewo  于 2023-03-11  发布在  PHP
关注(0)|答案(1)|浏览(119)

我正在尝试创建一个PHP路由器的网站与2页的Apache服务器。但我不断运行到NOT FOUND The requested URL was not found on this server。以下是我的代码结构。
文件夹结构

/var/www/html/project_folder
| .htaccess
| app
    | index.php
    | page1.php
    | page2.php
    | 404.php

index.php

<?php

$request_uri = explode('/', parse_url($_SERVER['REQUEST_URI']));
$requested_page = $request_uri[2];

if ($requested_page === '' || $requested_page === 'page1') {
   $route = '/page1.php';} 
elseif ($requested_page === 'page2') {
   $route = '/page2.php';
} else {    
   $route = '/404.php'; 
}

require __DIR__ . $route;

page1.php/page2.php-相似内容

<?php 
echo '<h1>Page No: 1</h1>';

.htaccess网站

RewriteEngine On
  RewriteBase /app/
  RewriteRule ^index\.php$ - [L]
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteRule . /project_folder/app/index.php [L,QSA]

当我在本地主机localhost/project_folder/applocalhost/project_folder/app/page2上运行相同的设置时,页面被呈现。
1.当我尝试默认路径www.myWebPageName.com/app/时,page 1呈现成功
1.当我尝试使用www.myWebPageName.com/app/page1在服务器上运行时,我得到了NOT FOUND

s4chpxco

s4chpxco1#

您不需要在RewriteRule中包含/project_folder/app/,因为您已经在使用RewriteBase

RewriteEngine On
RewriteBase /app/
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule . index.php [L,QSA]

编写它的方式与说(没有RewriteBase)相同:
RewriteRule . /app/project_folder/app/index.php [L,QSA]
上面的答案很好地解释了你想要达到的目标:How does RewriteBase work in .htaccess

相关问题