2016-09-13 96 views
0

我几乎完成了找到一种方法来仅在某些页面上显示.html文件。服务器请求uri页面和相关页面

在这种情况下,我想的test.html要在http://www.example.com/categories/AnyPageThatExcistsInCategories

我想通了,下面的代码工作在/类别列示。 <?php if ($_SERVER['REQUEST_URI'] == '/categories/') { include 'test.html';} ?>

我只需要关于如何得到它也在努力像/分类/ ThisCanBeAnything和类别/ ThisCanBeAnything/AndThisAlso等等等等 服务器配置页面是nginx的金色尖。

谢谢

+0

我不确定你的服务器环境,但是如果你使用Apache并且启用了重写模块,你可以这样做。 – Progrock

+0

抱歉忘了提及它。它运行在nginx上。 我提供的代码确实工作完美,但只在/类别和不/类别/ AnythingElse。 – razz

+0

您可以在nginx下使用重写规则:https://www.nginx.com/blog/creating-nginx-rewrite-rules/ – Progrock

回答

1

你可以看到,如果请求URI以字符串 '/分类/' 开头:

<?php 

$request_uri = '/categories/foo'; 

if (strpos($request_uri, '/categories/') === 0) 
{ 
    include 'your.html'; 
} 

替代的$ REQUEST_URI以上$_SERVER['request_uri']值。假设你在前端控制器中有这个逻辑。

另外:

<?php 

$request_uris = [ 
    '/categories/foo', 
    '/categories/', 
    '/categories', 
    '/bar' 
]; 

function is_category_path($request_uri) { 
    $match = false; 
    if (strpos($request_uri, '/categories/') === 0) 
    { 
     $match = true; 
    } 

    return $match; 
} 

foreach ($request_uris as $request_uri) { 
    printf(
     "%s does%s match a category path.\n", 
     $request_uri, 
     is_category_path($request_uri) ? '' : ' not' 
    ); 
} 

输出:

/categories/foo does match a category path. 
/categories/ does match a category path. 
/categories does not match a category path. 
/bar does not match a category path. 

在使用中:

if(is_category_path($_SERVER['REQUEST_URI'])) { 
    include 'your.html'; 
    exit; 
} 

您可能需要确切的字符串 '/类别/' 不匹配,如果这样你可以调整条件:

if(
    strpos($request_uri, '/categories/') === 0 
    &&      $request_uri !== '/categories/' 
) {} 
+0

出于某种原因,它显示了网站上所有页面上的html。 ps。 “foo”在这里'$ request_uri ='/ categories/foo';'可以是我不知道的任何东西,一个数字,一个字母,也许是组合的。 – razz

+0

一个假设你有'$ request_uri = $ _SERVER ['REQUEST_URI']',而不是上面给出的固定值。你也想在包含之后退出。 – Progrock

0

Progrock的例子可以正常工作,但这里是另一个使用正则表达式匹配而不是strpos的例子,以防万一您好奇!

<?php 
if (preg_match("/\/categories\/.*/", $_SERVER['REQUEST_URI'])) { 
    include 'test.html'; 
} 
?> 
+0

但在我的情况下,你的答案是唯一有效的答案。 感谢大家的帮助。 – razz

+0

您可能想要将该正则表达式模式锚定到字符串的开头:'“/^\/categories \ /.*/”' – Progrock