auto redirect to clean urls

2019-05-18 12:52发布

how can i auto redirect a site from dirty url to clean url in php , something like

http://www.mysite.com?page=page1&action=action1

to

http://www.mysite.com/page1/action1

3条回答
地球回转人心会变
2楼-- · 2019-05-18 13:28

try

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

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

查看更多
疯言疯语
3楼-- · 2019-05-18 13:35

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]
查看更多
Deceive 欺骗
4楼-- · 2019-05-18 13:42

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.

查看更多
登录 后发表回答