你能帮我创建一个 htaccess 和 php 函数吗?它应该可以创建看起来友好的 URL,例如 site.com/en/category/product
该网站将是多语言的,因此所有类别和产品名称都将进行本地化。
数据库将包含每种语言的记录 - product_id、category_id、name_en、category_en、name_de、category_de
等。
因此数据库记录为:product_id - 05、category_id - 01、name_en - Coffee05、category_en - 咖啡和茶、name_de - kaffee05、category_de - kaffee-und-tee
因此,URL /product.php?lang=en&category=01&product=05
应变为 /product/coffee-and-tea/coffee05
,对于 DE /产品/kaffee-und-tee/kaffee05
欢迎任何建议!
最佳答案
前几天我正在研究这个。这是我最终使用的:
.htaccess
RewriteEngine on
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php?url=$1 [L,QSA]
这会将所有流量发送到 index.php,其中包含 $_SERVER['REQUEST_URI']
的变量 url 为 $_GET['url']
。
然后我使用了以下函数:
function url(){
if(isset($_GET['url'])){
$routes = [];
// get the URL from the base defined in the.htaccess file.
// filter url
# Example: www.yourdomain.com/example-page/hello/1/title/
$url = filter_var(trim($_GET['url']),FILTER_SANITIZE_URL);
// delete last / if it is there.
$url = rtrim($url,'/');
# Exampele change 1: $url = example-page/hello/1/title
/*
* Remove the - (dash) in the url : EX. example-page/hello. Classnames can't have the - (dash) so class is written as examplePage.
* to call the function we need to remove the - (dash)
*/
# Example change 2: $url = examplepage/hello/1/title
$url = str_replace('-','', $url );
// create array with all the url parts.
# Example change 3: $url = ["examplepage","hello",1,"title"]
$url = explode('/',$url);
// add all array values to the var routes.
foreach($url as $value){
$routes[] = $value;
}
}
return $routes;
}
此函数从 $_GET['url']
返回一个数组。从那里,在index.php上,您可以基于数组中的第一项include
文件,以及为以下值分配值(或使用它们的索引)并决定如何处理那里的数据。
例如:
如果我的页面返回 example.org/products/12
,
我调用该函数:
$url = url();
$page = $url[0];
$id = $url[1];
include($page);
echo productData($id);
关于php - 带有本地化名称 ID 的友好 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45817597/