PHP .htaccess - >漂亮的网址(反向)

时间:2011-04-06 21:59:25

标签: php mod-rewrite rewrite friendly-url

我知道如何进行URL重写,例如: www.example.com/index.php?id=1&cat=3www.example.com/1/3/(或其他)。我知道。

我不知道的是如何在所有页面中更改我的所有链接以链接到漂亮的URL。我所有网站的链接都是旧时尚(<a href="index.php?id=1&cat=2">),而且还有很多。

如果用户点击index.php?id = 1,我问是否有人有想法或知道如何自动重定向到那个漂亮的URL。 (如果你在网址中更改标题,几乎就像这个网站Stackoverflow一样。)

所以我的预言是......

  1. 使用.htaccess读取index.php?id = 1&amp; cat = 2来重写索引/ 1/3本身再次解释(奇怪)

  2. 一个php文件,用于执行htaccess重写为原始重定向的重定向...

  3. 结论:将<a href="index.php?id=1&.....">自动更改为index/1/2


    解决

    Options +FollowSymLinks
    RewriteEngine On
    RewriteBase /
    
    ##################################
    # This turns index.php?id=1&cat=2 into index/1/2 and then back 'transparent' into    index.php?id=1&cat=2 if you have old fashioned
    # links in your site and don't want to change them :)
    
    
    # Avoid mod_rewrite infinite loops 
    # This is critical if you want to use this code
    
    RewriteCond %{ENV:REDIRECT_STATUS} 200
    RewriteRule .* - [L]
    
    # Hard-rewrite ("[R]") to "friendly" URL.
    # Needs RewriteCond to match original querystring.
    # Uses "?" in target to remove original querystring,
    #   and "%n" backrefs to move its components.
    # Target must be a full path as it's a hard-rewrite.
    RewriteCond %{QUERY_STRING} ^id=(\d+)&cat=(\d+)$
    RewriteRule ^index.php$ http://localhost/index/%1/%2/? [L,R]
    
    # Soft-rewrite from "friendly" URL to "real" URL.
    # Transparent to browser.
    # Won't re-trigger the above rewrite, though I'm
    #   not really sure why! The order of the rules
    #   doesn't seem to make a difference.
    RewriteRule ^index/(\d+)/(\d+)/$ index.php?id=$1&cat=$2 [L]
    

2 个答案:

答案 0 :(得分:3)

RewriteEngine on

# Prevents browser looping, which does seem
#   to occur in some specific scenarios. Can't
#   explain the mechanics of this problem in
#   detail, but there we go.
RewriteCond %{ENV:REDIRECT_STATUS} 200
RewriteRule .* - [L]

# Hard-rewrite ("[R]") to "friendly" URL.
# Needs RewriteCond to match original querystring.
# Uses "?" in target to remove original querystring,
#   and "%n" backrefs to move its components.
# Target must be a full path as it's a hard-rewrite.
RewriteCond %{QUERY_STRING} ^id=(\d+)&cat=(\d+)$
RewriteRule ^index\.php$ http://example.com/index/%1/%2/? [L,R]

# Soft-rewrite from "friendly" URL to "real" URL.
# Transparent to browser.
RewriteRule ^index/(\d+)/(\d+)/$ /index.php?id=$1&cat=$2

当然,理想情况下,您只需修复链接,然后您只需要进行软重写。 :)

使用Apache / 2.2.3进行测试。我认为我编写了“硬重写”和“软重写”这两个术语。

答案 1 :(得分:0)

为什么不直接更改index.php文件呢?理论上,您可以通过这种方式进行更多错误检查,允许变量按任意顺序排列并仍然路由到正确的结束位置。

<?php
    // Permanent redirection
    header("HTTP/1.1 301 Moved Permanently");
    header("Location: http://www.example.com/{$_GET['id']}/{$_GET['cat']}");

我这里没有做任何错误检查,但是想给出一个基础示例。

第二个想法我想这是在index.php文件中增加了你想要用于你的应用程序本身的功能,所以它可能最终会混淆代码中的功能。

相关问题