【问题标题】:Smart URL with optional parameters?带有可选参数的智能 URL?
【发布时间】:2014-06-03 09:14:09
【问题描述】:

我目前在我的 .htaccess 文件中有这个:

RewriteEngine On 
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f 
RewriteCond %{REQUEST_FILENAME} !-l
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(\w+)(/(\w+))?/?$ route.php?1=$1&2=$3 [L]

所以我可以使用myurl.com/foo/bar(/) 或只是myurl.com/foo(/)(可选斜杠,不能丢失)

我对正则表达式不是很熟悉,所以我如何让这个最多允许大约 6 个参数(myurl.com/one/two/three/four/five/six)

【问题讨论】:

    标签: php regex .htaccess url


    【解决方案1】:
    RewriteRule ^(\w+)(?:/(\w+))?(?:/(\w+))?(?:/(\w+))?(?:/(\w+))?(?:/(\w+))?/?$ route.php?1=$1&2=$2&3=$3&4=$4&5=$5&6=$6 [L]
    

    您可以查看here


    要在参数中允许空格,您可以使用:

    RewriteRule ^([\w\ ]+)(?:/([\w\ ]+))?(?:/([\w\ ]+))?(?:/([\w\ ]+))?(?:/([\w\ ]+))?(?:/([\w\ ]+))?/?$ route.php?1=$1&2=$2&3=$3&4=$4&5=$5&6=$6 [L]
    

    【讨论】:

    • 它可以工作,但现在参数中的空格不起作用。这很糟糕。
    • 你的意思是myurl.com/one/two and a half/three??
    • 是的。它只是进入 404 页面而不是 route.php。
    • [\w ]+替换每个\w+
    • “500 Internal Server Error”当我按照你说的那样替换时。
    猜你喜欢
    • 2019-03-11
    • 2020-01-30
    • 2021-09-09
    • 2012-04-22
    • 2014-02-16
    • 2016-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多