【问题标题】:URL Rewrite (multi language) with .htaccess使用 .htaccess 重写 URL(多语言)
【发布时间】:2012-05-14 21:57:27
【问题描述】:

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

我想要以下:

/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

重写规则是什么样子的?

感谢您的帮助和/或建议!

【问题讨论】:

    标签: .htaccess url rewrite


    【解决方案1】:

    如果您不想将所有可能的翻译列表(catalog-katalog、view-something 等)包含在 .htaccess 文件中,创建单独的 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";
    }
    

    【讨论】:

    • 您好,非常感谢您的回复!不错的解决方案,但最好我希望它在 .htaccess
    • 如果您只有几个部分,您可以为每种语言和部分组合执行RewriteRule ^en/SECTIONNAME/(.+)\.html$ SECTIONSCRIPT.php?lang=en&amp;id=$1 [L,QSA] 之类的操作,例如:RewriteRule ^de/katalog/(.+)\.html$ catalog.php?lang=de&amp;id=$1 [L,QSA]
    猜你喜欢
    • 1970-01-01
    • 2021-06-17
    • 2020-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多