开发者

Pros/cons of using index.php?q=path/ instead of index.php/path/ when routing URLs?

I'm writing a simple method to map routes to files and I've come across two ways to do it.

The first, and I guess used by most frameworks, is using the $_SERVER['REQUEST_URI'] variable to extract everything after index.php:

RewriteRule ^(.*)$ index.php [QSA,L]

The second way is used in Drupal, and the route is simply passed as a query string.

RewriteRule ^(.*)$ index.php?q=$1 [QSA,L]

Now, the "Drupal way" seems a lot simpler to me. With the other method you'd have to use "explode" on both $_SERVER['REQUEST_URI'] and $_SERVER['SCRIPT_NAME'] and then use something like array_diff_assoc to remove the script name and subdirectory name, if there is one. It's not THAT much work, but if with the Drupal way you can simply extract the $_GET['q'] value, why nobody does it that way? What are the d开发者_运维技巧isadvantages, if any?

Thanks.


The disadvantage of using a q param is, without URL rewriting the URL will look like...

http://domain.com/?q=something

...as opposed to the cleaner (IMO)...

http://domain.com/index.php/something


There is no huge advantage or disadvantage one way or the other with the url being rewritten. However, I will point out everything including and after the final slash is stored in _SERVER[PATH_INFO], so parsing the request URI my not be necessary.


The reason that the shorter URL technique is used mostly is for the cleaner technique and the better SEO that comes from it. Search engines consider these two URL's to "be the same":

http://www.domain.com/?b=something

http://www.domain.com/?b=hello

I do not have a good explanation so here are some links with some really good information on it:

  • http://blog.hubspot.com/blog/tabid/6307/bid/2261/My-Wife-says-Short-URLs-Yield-Better-Click-Through-Rates-in-SEO-and-she-s-RIGHT.aspx
  • Short URL or long URL for SEO
  • http://googlewebmastercentral.blogspot.com/2008/09/dynamic-urls-vs-static-urls.html

Now some people implement the shorter URL's differently, but this is how I have found them to work the best for me:

In .htaccess

RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule ^(.*)$ index.php?route=$1 [L,QSA]

In index.php (or some other php file)

if(isset($_GET['route']) && $_GET['route'] != NULL && strlen($_GET['route']) > 0)
{
    $split = explode('/', $_GET['route']);
    for($i=1; $i <= count($split)-1; $i++)
    {
        $_GET[$i] = $split[$i];
    }
}

This then allows you to use $_GET['1'] (or $_GET[1]) and all subsequent numbers as well.

URL's then look like this:

http://www.domain.com/?b=something

becomes

http://www.domain.com/something

http://www.domain.com/?b=something&a=hello&c=blah

becomes

http://www.domain.com/something/hello/blah

And then the parameters can be accessed via:

$_GET[1] = "something";
$_GET[2] = "hello";
$_GET[3] = "blah";

Hope that helps!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜