REQUEST_URI返回单斜杠

时间:2018-04-13 10:11:51

标签: php

我使用此部分代码打印if (location.getSpeed > 4){ stratTrip(); } 代码:

canonical

但如果当前<?php if(!empty($_SERVER["REQUEST_URI"])){ $url = strtok($_SERVER["REQUEST_URI"],'?'); ?> <link rel="canonical" href="https://mywebsite.com<?=urldecode($url);?>" /> <?php } else { ?> <link rel="canonical" href="https://mywebsite.com" /> <?php } ?> else,则不会准备URL条件。我发现了原因,因为https://mywebsite.com返回var_dump($_SERVER["REQUEST_URI"]);。为什么当我打开此网址时string(1) "/"返回REQUEST_URI而尾部没有斜线?

无论如何,除了这个问题,我如何解决我的代码才能工作?

1 个答案:

答案 0 :(得分:3)

在HTTP通话中,$_SERVER['REQUEST_URI']永远不能是empty,除非脚本本身为unset($_SERVER['REQUEST_URI'])$_SERVER['REQUEST_URI] = ''

对于http://mywebsite.com的HTTP调用,它将保留/作为其值。这就是你得到的。 /表示网站的根目录,因此当向网站的根目录发出HTTP请求时,/将作为路径发送,并且始终存在,无论您是否将其添加到网址中。

我认为这澄清了为什么你没有达到代码的else条件。

出现问题,如果你想在没有任何查询参数的情况下将路径附加到url,那么更好的方法应该是:

<link rel="canonical" href="https://mywebsite.com<?php echo parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH); ?>">

这将取代您的所有代码。您可能需要查看PHP的parse_url函数。

如果您不想故意使用尾部斜杠,则可以使用rtrim

<link rel="canonical" href="https://mywebsite.com<?php echo rtrim(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH), '/'); ?>">

如果您将任何有效的URL传递给parse_url,并且不希望仅对root用户进行尾部斜杠,则:

<?php
$path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
if($path == '/' || !$path) {
  $path = '';
} ?>
<link rel="canonical" href="https://mywebsite.com<?php echo $path; ?>">
相关问题