如何在不影响URL的情况下加载不同目录中的页面

时间:2016-06-09 14:50:21

标签: php .htaccess

我的文件结构通常是这样的 -

/images/  
/css/  
init.php  
header.php  
page1.php  
page2.php 
等等......

在基本上创建了越来越多的页面之后,管理它们变得更加困难,因为它实际上将根目录变成了大量的页面列表。

我该怎么做才能将页面放在一个文件夹中及其相关的类别 -

/pages/category1/page1.php  
/pages/category1/page2.php  
/pages/category2/page3.php   

不影响网址,因此它仍然看起来像http://domain.com/page1.php

编辑.htaccess是最有效的方法吗?还是有另一种方式?

1 个答案:

答案 0 :(得分:0)

我在根目录中创建了一个单独的php文件,它基本上从$ _GET请求获得了一个PHP页面,然后检查了PHP页面是否存在。如果是,那么我使用REQUIRE_ONCE来获取页面。

//Get page from $_GET request 
if (isset($_GET['page'])){
  $page = $_GET['page'];
}

//Create path including the page
$url = ROOT_DIR . "/pages/".$page;

//If the page exists include it, if not then show a 404 page.
if(file_exists($url)){
  REQUIRE_ONCE $url;
}else{
  REQUIRE_ONCE "/pages/404.php";
}

这允许我使用

访问/ pages /目录中的login.php
 http://domain.com/index.php?page=login.php

然后我用.htaccess重新编写了URL,使其更具吸引力。

RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)/?$ index.php?page=$1.php [QSA,L]

这样我就可以使用

 http://domain.com/login