PHP .htaccess -> pretty url (in reverse)

自作多情 提交于 2019-11-27 20:55:57
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".

Why not just change your index.php file to do it? You could theoretically do a little more error checking that way, allowing for the variables to be in any order and still get routed to the correct end location.

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

I didn't do any error checking here, but wanted to give a base example.

On second thought I guess this is adding in functionality to the index.php file which you then want to use for your application itself, so perhaps it would end up confusing the functionality in the code.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!