使用.htaccess重写URL(多语言)

时间:2012-05-14 11:43:27

标签: .htaccess url rewrite

我正在试图找出一个URL Rewrite,但我对重写规则完全无用。

我想要以下内容:

/en/catalog/myname.html -> /catalog.php?id=myname&lang=en
/de/katalog/myname.html -> /catalog.php?id=myname&lang=de
/en/view/123 -> /view.php?id=123&lang=en

重写规则如何?

感谢您提供任何帮助和/或建议!

1 个答案:

答案 0 :(得分:1)

如果您不想在.htaccess文件中包含所有可能的翻译列表(catalog-katalog,view-something等),则可以更轻松地创建单独的php脚本,该脚本将处理路由。例如:

RewriteRule ^(en|de)/([^/]+)/(.+)\.html$ router.php?lang=$1&section=$2&id=$3 [L,QSA]

router.php可以是例如:

<?php

// List of translations
$german = array(
    'katalog' => 'catalog',
    'something' => 'view', 
    ...
);

// List of available sections
$allowed = array('catalog', 'view');

$section = $_GET['section'];
if ($_GET['lang'] === 'de') {
    $section = isset($german[$section])? $german[$section] : NULL;
}

// IMPORTANT: Include PHP file only if section param is listed in $allowed!
// Otherwise attacker could execute any file on the server 
// by opening /router.php?section=badfile

if (in_array($section, $allowed)) {
    include dirname(__FILE__) . "/$section.php";

} else {
    header('HTTP/1.x 404 Not Found');
    print "Page not found";
}