【问题标题】:.htaccess or php redirect to friendly url when index.php?*=* is accessed directly直接访问 index.php?*=* 时 .htaccess 或 php 重定向到友好的 url
【发布时间】:2013-02-24 23:45:15
【问题描述】:

我正在为我的游戏网站进行新设计,我所做的是制定了重写规则:

RewriteRule ^play/([^/\.]+)/?$ index.php?play=$1 [L]

当用户打开位于地址栏(规范 url)中的 /play/gamename 并使用我的 index.php 加载游戏页面时,这非常有效。

但是,我现在想做的是,当用户访问旧网址 (index.php?play=gamename) 时,他们应该被重定向到新的规范网址 (/play/gamename)。

有人可以帮我输入代码吗?我愿意同时使用 .htaccess 文件或 index.php 文件来执行此操作,无论哪个效果最好。

另一个问题是我已经有很多 facebook cmets 和 likes,它们引用 index.php?play=gamename 页面,是否也可以以某种方式将这些喜欢和 cmets 移动到新的更漂亮的 url?

【问题讨论】:

    标签: php facebook redirect


    【解决方案1】:

    我认为您会寻找这样的东西来从旧 URL 重定向到新 URL,同时将该 URL 保持为提供脚本的实际位置。

    Options +FollowSymlinks
    RewriteEngine On
    
    RewriteBase /
    
    # Stop rewrite from doing an infinite loop by rejecting redirects
    RewriteCond %{ENV:REDIRECT_STATUS} !=200
    RewriteCond %{REQUEST_URI}  ^/index\.php$
    RewriteCond %{QUERY_STRING} ^play=(.*)$
    RewriteRule .* /play/%1? [NC,R=301,L]
    
    # Rewrite all requests from /play/ to index.php
    RewriteRule ^play/(.*)$ /index.php?play=$1 [NC,L]
    

    至于 facebook,您无法对旧的 cmets 做任何事情,但您的重写会为您的网站的任何未来点击处理。

    【讨论】:

      【解决方案2】:

      在 php 中执行此操作的方法如下:

      这个函数检查页面是否被直接查看。

      function directviewcheck(){
          $requestingurl = $_SERVER['REQUEST_URI'];
          $phpself = $_SERVER['PHP_SELF'];
          $phpselflength = strlen($phpself);
          $resulturlcrop = mb_substr($requestingurl, 0, $phpselflength);
      
          if( $resulturlcrop == $phpself ){
              return true;
          }else{
              return false;
          }
      }
      

      这将告诉您浏览器中的 url 是否与文件名匹配。如果这样做,它将返回 true。

      接下来在 index.php 中调用它:

      if( directviewcheck() == true ){
          // your redirect code
          // Something like this should work
      
          $gamename = $_GET['play'];
          header("HTTP/1.1 301 Moved Permanently")
          header("Location: http://www.yoursite.com/play/" . $gamename );
          exit;  // make sure you use exit or its alias die to prevent the page from showing.
      
      }
      

      旧链接将转到新页面,并且仍然通过旧链接访问您的内容的搜索引擎会知道删除它们并将新链接编入索引。

      如果您需要更动态的位置变量,您可以创建一个位置变量,然后根据用途将其放入 header() 中。

      无论如何,您的问题已经过时,但也许对您或其他人仍然有用。

      ====

      在 .htaccess 中,sjdaws 看起来可以工作。

      ====

      就您的 Facebook 而言,我看到了这些: Facebook like count resets after a 301 redirection 或者 How to manage 'Like' button for URLs that can change slightly?

      【讨论】:

        猜你喜欢
        • 2014-02-24
        • 1970-01-01
        • 1970-01-01
        • 2018-04-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-15
        • 1970-01-01
        相关资源
        最近更新 更多