PHP .htaccess -> pretty url (in reverse)

后端 未结 2 1189
半阙折子戏
半阙折子戏 2020-12-05 16:37

I know how to make URL\'s rewrite, for example: www.example.com/index.php?id=1&cat=3 to www.example.com/1/3/ (or whatever). I know that.

2条回答
  •  一整个雨季
    2020-12-05 17:12

    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
    

    Of course, ideally, you'd just fix your links, and then you'd only require the soft-rewrite. :)

    Tested with Apache/2.2.3. I think I made up the terms "hard-rewrite" and "soft-rewrite".

提交回复
热议问题