【问题标题】:How can i split URL with htaccess如何使用 htaccess 拆分 URL
【发布时间】:2013-02-27 23:39:29
【问题描述】:

例如:
google.com/en/game/game1.html
应该是
google.com/index.php?p1=en&p2=game&p3=game1.html

如何拆分 URL 并发送 index.php 的“/”部分?

【问题讨论】:

    标签: .htaccess url split


    【解决方案1】:

    只有在查询参数是固定长度时才能实现这一点。否则还有其他方法,但需要在应用程序中解析路径。

    固定长度实现

    以下规则匹配所有三个 URL 部分,然后将它们重写为 index.php 的命名查询参数。

    RewriteRule ^([^/]+)/([^/]+)/(.+)$ index.php?p1=$1&p2=$2&p3=$3
    

    这重写:

    /en/game/game1.html
    

    收件人:

    /index.php?p1=en&p2=game&p3=game1.html
    

    未知长度实现

    # Don't rewrite if file exist. This is to prevent rewriting resources like images, scripts etc
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule .* index.php?path=$0
    

    这重写:

    /en/game/game1.html
    

    收件人:

    /index.php?path=en/game/game1.html
    

    然后你就可以解析应用中的路径了。


    编辑:) 为了使重写规则仅在 URL 的第一级包含两个字符时匹配,请执行以下操作:

    RewriteRule ^([a-zA-Z]{2})/([^/]+)/(.+)$ index.php?p1=$1&p2=$2&p3=$3
    

    您也可以为 unknown length 实现这样做:

    RewriteRule ^[a-zA-Z]{2}/ index.php?path=$0
    

    【讨论】:

    • 我如何确定 URL“en/”的第一部分是 2 个字符?所以所有语言都是 2 个字母,如果 URL 是 3 个字母,比如“enw/”重写不应该工作?
    猜你喜欢
    • 2014-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-17
    相关资源
    最近更新 更多