PHP如何显示纯URL

时间:2012-04-30 09:30:15

标签: php javascript url seo

我正在使用一些Javascript和PHP来获取浏览器视口,并根据访问者的浏览器/设备动态提供合适的布局。我的index.php文件是这样的:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>

<body>

<?php
if (isset($_GET['width']) AND isset($_GET['height'])) {
  $layoutWidth = $_GET['width'];
      if ( $layoutWidth >= 240 && $layoutWidth <= 900 ) {
        require_once('layout1.php');
      } else {
         require_once('layout2.php');
      }
} else {
  echo "<script language='javascript'>\n";
  echo "  location.href=\"${_SERVER['SCRIPT_NAME']}?${_SERVER['QUERY_STRING']}"
            . "&width=\" + document.documentElement.clientWidth;\n";
  echo "</script>\n";
  exit();
}
?>
</body>
</html>

输出网址如下:

http://mydomain.com/index.php?&width=1600&height=812

我正在寻找的方法是使此网址如下所示:

http://mydomain.com/

有可能这样做吗?如果是,那么如何?

任何PHP或Plain JavaScript解决方案都可以

(没有jQuery或MooTools或任何此类库,因为这是我整个网站中唯一的JavaScript函数,加载50到100 KB的库只是为了完成这个小任务,没有任何意义。)< / em>的

请帮忙

1 个答案:

答案 0 :(得分:0)

您应该能够使用.htaccess重写URL(代码不包括常见资源类型和index.php循环):

# Turn rewriting on
Options +FollowSymLinks
RewriteEngine On
# Redirect requests to index.php
RewriteCond %{REQUEST_URI} !=/index.php
RewriteCond %{REQUEST_URI} !.*\.png$ [NC]
RewriteCond %{REQUEST_URI} !.*\.jpg$ [NC]
RewriteCond %{REQUEST_URI} !.*\.css$ [NC]
RewriteCond %{REQUEST_URI} !.*\.gif$ [NC]
RewriteCond %{REQUEST_URI} !.*\.js$ [NC]
RewriteRule .* http://mydomain.com/

然后使用$_SERVER["REQUEST_URI"]访问实际请求的URI,您可以从中解析高度和宽度值。例如

$height = 0;
$width = 0;
$requestParts = explode('?', $_SERVER['REQUEST_URI']);
$requestParts = explode('&', $requestParts['1']);
foreach ($requestParts as $requestPart) {
    $getVarParts = explode('=', $requestPart);
    if ($getVarParts['0'] == 'height') {
        $height = $getVarParts['1'];
    } else if ($getVarParts['0'] == 'width') {
        $width = $getVavParts['1'];
    }
}