dpy3846 2015-01-04 14:51
浏览 73
已采纳

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

I'm running into a very common issue, I need to transform my site.com/page.php?id=1&title=page-title into site.com/page-title-id

I was thinking this could be easily done adding some mod_rewrite in the .htaccess file but I'm feeling it might not be the most SEO-friendly approach there is, what do you think?

Another way would be to make some changes within the PHP code, but I'm relatively new to this language and I don't know about all the libraries and functions that come with PHP and could make my life easier here.

So far, what I'm doing (Which is not working) in my .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>

And my page.php has

//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>';
    }

I guess a solution in PHP would be much better because I don't want to make search engines think I'm cloaking the site or redirecting or anything, just want the URL to be like site.com/page-title-id or similar.

EDIT: Tried a different approach within the .htaccess

  • 写回答

1条回答 默认 最新

  • dpo15099 2015-01-04 15:22
    关注

    I need to transform my site.com/page.php?id=1&title=page-title into site.com/page-title-id

    You can replace your current htaccess code by this one (assuming it is located in document root folder)

    <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>
    

    This code will redirect old url format (http://example.com/page.php?id=1&title=page-title) to its new format (http://example.com/page-title-1) and will then internally rewrite back new format to old format (without any infinite loop)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 组策略中的计算机配置策略无法下发
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)