将GET vars从PHP转换为友好的URL?

时间:2015-01-04 14:51:49

标签: php apache .htaccess mod-rewrite

我遇到了一个非常常见的问题,我需要将我的site.com/page.php?id=1&title=page-title转换为site.com/page-title-id

我认为可以很容易地在.htaccess文件中添加一些mod_rewrite,但我觉得它可能不是最适合搜索引擎优化的方法,您怎么看?

另一种方法是在PHP代码中进行一些更改,但我对这种语言相对较新,而且我不了解PHP附带的所有库和函数,可以让我的生活这里更容易。

到目前为止,我在.htaccess中所做的事情(哪些不起作用):

# BEGIN ocasion_system
<IfModule mod_rewrite.c>
Options +FollowSymLinks -MultiViews
# Turn mod_rewrite on
RewriteEngine On
RewriteBase /

RewriteCond %{THE_REQUEST} ^GET\ /[^?\s]+\.php\?title=([^&\s]+)&?
RewriteRule (.*)\.php$ /$1/%1/? [L,R=301]

RewriteRule ^([^/]+)/([^/]+)/$ $1.php?title=$2 [QSA,L]
</IfModule>

我的page.php有

//all includes up here..
$page = new Page();
$page->__set('title', $_GET["title"]); //this is how i set up my page interface, please don't laugh

if ($_GET["title"] != NULL){    
        $page = get_page($page, $db);       
        echo '<pre>';
        print_r($page);//works as intended when i access http://localhost/page.php?title=default prints all the Page object with that title.
        echo '</pre>';
    }

我想PHP中的解决方案会好得多,因为我不想让搜索引擎认为我隐藏了网站或重定向或任何东西,只是想让网址像site.com/ page-title-id或类似。

编辑:在.htaccess

中尝试了不同的方法

1 个答案:

答案 0 :(得分:1)

  

我需要将 site.com/page.php?id=1&title=page-title 转换为   的 site.com/page-title-id

您可以用这个替换当前的htaccess代码(假设它位于文档根文件夹中)

<IfModule mod_rewrite.c>
  Options +FollowSymLinks -MultiViews

  # Turn mod_rewrite on
  RewriteEngine On
  RewriteBase /

  RewriteCond %{THE_REQUEST} \s/page\.php\?id=([0-9]+)&title=([^\s&]+)\s [NC]
  RewriteRule ^ %2-%1? [R=301,L]

  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteRule ^([^/]+?)-([0-9]+)$ page.php?id=$2&title=$1 [L]
</IfModule>

此代码会将旧的url格式(http://example.com/page.php?id=1&title=page-title)重定向到其新格式(http://example.com/page-title-1),然后在内部将新格式重写为旧格式(没有任何无限循环)