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 ats2837 spi2从机的代码
  • ¥200 wsl2 vllm qwen1.5部署问题
  • ¥100 有偿求数字经济对经贸的影响机制的一个数学模型,弄不出来已经快要碎掉了
  • ¥15 这个公式写进SIMULINK中的function模块的代码中应该是什么样的
  • ¥15 javaweb登陆的网页为什么不能正确连接查询数据库
  • ¥15 数学建模数学建模需要
  • ¥15 已知许多点位,想通过高斯分布来随机选择固定数量的点位怎么改
  • ¥20 nao机器人语音识别问题
  • ¥15 怎么生成确定数目的泊松点过程
  • ¥15 layui数据表格多次重载的数据覆盖问题