2015-01-04 64 views
3

我遇到一个很常见的问题,我需要改变我的site.com/page.php?id=1 &标题=页面标题为site.com/page-title-id将PHP的GET变量转换为友好的URL?

我认为这可以很容易地在.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

目前还不清楚你想要什么这样做,但这里有一些想法。 (1)为此使用htaccess是很好的;它实际上比尝试单独在PHP中完成更好。 (2)你的'RewriteRule'没有任何'title'参数,但这就是你在PHP脚本中寻找的东西。 – 2015-01-04 15:04:54

+0

@EdCottrell取决于。我通常更喜欢将所有请求重定向到'index.php',并且有一个完善的'Router'对象来处理我的路由。 – 2015-01-04 15:05:44

+0

@SecondRikudo我可能应该更清楚。我和你一样,但你仍然需要以某种方式进行重定向,通常是htaccess。无论如何,它与隐形无关。 – 2015-01-04 15:08:01

回答

1

我需要改变我的site.com/page.php?id=1 &标题=页面标题site.com内的不同的方法/页标题-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),然后将在内部重写回新格式的旧格式(没有任何无限循环)

+0

好吧我将我的.htaccess移到了我的index.php文件所在的位置,并且仍然不起作用,我会更详细地介绍Apache配置文档,并在您获得正确工作后立即将您的问题标记为正确。谢谢。 – octohedron 2015-01-04 15:43:04

+0

对不起,但是当我去site.com/page/default-2它不断给404消息:\ – octohedron 2015-01-04 15:59:32

+0

你没有提到'/ page /'子文件夹,所以这段代码不能工作。请提供您需要的真实网址(旧格式和新格式) – 2015-01-04 16:02:39