auto redirect to clean urls

我的梦境 提交于 2019-12-06 11:52:24

You have to check if it was clean request or not. Otherwise you will fall into infinite loop

Here is an example from one of my projects:

.htaccess

RewriteEngine On
RewriteRule ^game/([0-9]+)/ /game.php?newid=$1

game.php

if (isset($_GET['id'])) {
  $row = dbgetrow("SELECT * FROM games WHERE id = %s",$_GET['id']);
  if ($row) {
    Header( "HTTP/1.1 301 Moved Permanently" ); 
    Header( "Location: /game/".$row['id']."/".seo_title($row['name'])); 
  } else {
    Header( "HTTP/1.1 404 Not found" ); 
  }
  exit;
}

if (isset($_GET['newid'])) $_GET['id'] = $_GET['newid'];

So, you have to verify, if it was direct "dirty" call or rewritten one.
And then redirect only if former one.
You need some code to build clean url too.

And it is also very important to show 404 instead of redirect in case url is wrong.

If you are running Apache you can use the mod_rewrite module and set the rules in a .htaccess file in your httpdocs folders or web root. I don't see any reason to invoke a PHP process to do redirection when lower level components will do the job far better.

An example from Simon Carletti:

RewriteEngine On
RewriteCond %{REQUEST_URI}  ^/page\.php$
RewriteCond %{QUERY_STRING} ^id=([0-9]*)$
RewriteRule ^(.*)$ http://mydomain.site/page/%1.pdf [R=302,L]

try

header("Location: http://www.mysite.com/".$_GET['page']."/".$_GET['action']);

you should check whether the values are set before trying to redirect

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!