簡體   English   中英

PHP檢入函數以將非尾部斜杠URL重定向到尾部斜杠URL

[英]PHP check in a function to redirect a non-trailing slash URL to trailing slash URL

我有一個控制分頁的Wordpress內容並將編號的URL重定向到其父URL的函數。

該函數工作正常,但我希望重定向301的編號URL沒有最終的斜杠,直接觸發到斜杠網址。 例如:

https://www.example.com/how-to-do-something/1111

應立即重定向到

https://www.example.com/how-to-do-something/

目前,重定向301正在運行,但通過https://www.example.com/how-to-do-something然后轉到https://www.example.com/how-to-do-something/

但是, 與此同時 ,此檢查不應使帶有最終尾部斜杠的編號URL無效,這些已經很好,例如:

https://www.example.com/how-to-do-something/1111/一次性完全重定向到https://www.example.com/how-to-do-something/ 所以對那些人沒有任何作用。

功能如下:

global $posts, $numpages;

 $request_uri = $_SERVER['REQUEST_URI'];

 $result = preg_match('%\/(\d)+(\/)?$%', $request_uri, $matches);

 $ordinal = $result ? intval($matches[1]) : FALSE;

 if(is_numeric($ordinal)) {

     // a numbered page was requested: validate it
     // look-ahead: initialises the global $numpages

     setup_postdata($posts[0]); // yes, hack

 $redirect_to = isset($ordinal) ? '/': (($ordinal > $numpages) ? "/$numpages/" : FALSE);

     if(is_string($redirect_to)) {

         // we got us a phantom
         $redirect_url = get_option('home') . preg_replace('%'.$matches[0].'%', $redirect_to, $request_uri);

         // redirect to it's parent 301
             header($_SERVER['SERVER_PROTOCOL'] . ' 301 Moved Permanently');

         header("Location: $redirect_url");
         exit();

     }
 }

如何在調用htaccess規則的情況下從非尾隨斜杠URL直接到尾部斜杠實現這個PHP檢查 ,我必須強制使用尾部斜杠? 感謝您的耐心和時間。

Wordpress有一個添加尾部斜杠的功能:

trailingslashit($string);

再看一下你的代碼,有些東西沒有加起來:

  1. $redirect_to = isset($ordinal) ? '/': (($ordinal > $numpages) ? "/$numpages/" : FALSE); $redirect_to = isset($ordinal) ? '/': (($ordinal > $numpages) ? "/$numpages/" : FALSE); 將始終返回'/'因為$ ordinal始終在if語句中設置。

  2. 'home'選項是否返回帶斜杠的url? 確保你需要'trailingslashit'功能,即trailingslashit(get_option('home'))

  3. 總的來說,我會稍微改變一下。 這就是我要做的(隨意改變它以滿足您的需求):

$request_uri = $_SERVER['REQUEST_URI'];

$uriParts = explode('/', trim($request_uri, '/'));

$ordinal = array_pop($uriParts);

if (is_numeric($ordinal)) {
  setup_postdata($posts[0]);
  $redirect_url = trailingslashit(get_option('home')) . implode('/', $uriParts) . '/';
  header($_SERVER['SERVER_PROTOCOL'] . ' 301 Moved Permanently');
  header("Location: $redirect_url");
  exit();
}

希望這可以幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM