2016-09-13 95 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