What is the best way to implement a friendly URL that has multiple variables using mod_rewrite?

守給你的承諾、 提交于 2019-11-30 23:01:18

Normal practice is to map URLs with values in them to the parameterized URL. For example:

http://example.com/London/2/10-15
to
http://example.com/index.php?loc=London&type=2&priceCat=10-15

This can be done like so in .htaccess:

RewriteEngine on
RewriteRule ^([^/]+)/([^/]+)/([^/]+)$ /index.php?loc=$1&type=$2&priceCat=$3 [L]

I would avoid redirecting if at all possible. If you want completely different URLs to map to parameters, like your example (/something-here to /index.php?...) then all you need to do is rework your application so that you either pass the parameters to a function that displays the page, or set the variables and include another PHP file that does the processing.

Why do you redirect to that parameterized URL? Why don’t you just use that parameterized URL and return the actual contents?

So instead of doing a redirect, do something like this:

$url = 'http://example.com/index.php?loc=London&type=2&priceCat=10-15'; // resolved from http://example.com/find/SomethingHere-or-there
// split URL into its parts
$url = parse_url($url);
// check if requested file exists
if (is_file($_SERVER['DOCUMENT_ROOT'].$url['path'])) {
    // parse and merge URL parameters
    parse_str($url['query'], $params);
    $_GET = array_merge($_GET, $params);
    // include resolved file
    include $_SERVER['DOCUMENT_ROOT'].$url['path'];
} else {
    hedaer($_SERVER['SERVER_PROTOCOL'].' 404 Not Found');
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!