【问题标题】:htaccess rule that allows pass of empty query parameter允许传递空查询参数的 htaccess 规则
【发布时间】:2021-07-30 01:22:23
【问题描述】:

我需要以下 URL 结构。

https://url.com/info/cars/audi/fastest/1
https://url.com/info/planes/airbus/cheapest/1

这是当前的 .htaccess 规则:

RewriteRule ^info/(.*)/(.*)/(.*)/(.*)$ /info.php?category=$1&sub_category=$2&sorting=$3&page=$4

我需要参数 3 和 4 是可选的。目前,如果我将页面或子类别留空,则会返回 404 错误。但例如,我不想传递第一页的 page 参数。这意味着:

https://url.com/info/cars/ <----- this should be equal to sub-category: all, sorting: default, page: 1

https://url.com/info/cars/2 <----- this should be equal to sub-category: all, sorting: default, page: 2

我知道如何在 PHP 中实现,但这需要 .htaccess 规则正确。目前,一旦我将一个参数留空,它就会将我重定向到 404。

【问题讨论】:

    标签: php regex .htaccess


    【解决方案1】:

    有 4 条这样的独立规则:

    Options -Multiviews
    RewriteEngine On
    
    # 4 parameters rule
    RewriteRule ^info/([^/]+)/([^/]+)/([^/]+)/([^/]+)/?$ info.php?category=$1&sub_category=$2&sorting=$3&page=$4 [L,QSA,NC]
    
    # 3 parameters rule
    RewriteRule ^info/([^/]+)/([^/]+)/([^/]+)?$ info.php?category=$1&sub_category=$2&sorting=$3&page=1 [L,QSA,NC]
    
    # 2 parameters rule 1
    RewriteRule ^info/([^/]+)/(\d+)/?$ info.php?category=$1&sub_category=all&sorting=default&page=$2 [L,QSA,NC]
    
    # 2 parameters rule 2
    RewriteRule ^info/([^/]+)/([^/]+)/?$ info.php?category=$1&sub_category=$2&sorting=default&page=1 [L,QSA,NC]
    
    # 1 parameter rule
    RewriteRule ^info/([^/]+)/?$ info.php?category=$1&sub_category=all&sorting=default&page=1 [L,QSA,NC]
    

    【讨论】:

    • 到目前为止一切顺利,但没有考虑到 https://url.com/info/cars/2https://url.com/info/cars/audi/2 等,因此排序是可选的。对不起,忘了把它放在最初的帖子里!
    • 可选参数应该从末尾开始,否则规则如何知道缺少什么sub_categorysorting
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多