【问题标题】:.htaccess - writing efficient codes using chain, next for url redirects.htaccess - 使用链编写高效代码,接下来用于 url 重定向
【发布时间】:2011-08-04 17:38:09
【问题描述】:

假设我在用户浏览页面 (www.date.com) 上有如下 URL: www.date.com/Location-A/Education-B/Sex-C/Interest-D/

情况是用户只能浏览所有 (4) 个可用条件中的一个数(1 或 2) www.date.com/Education-B/ 或 www.date.com/Sex-C/Interest-E/

还假设 URL 中浏览条件的顺序很重要(即 A/B - ok,但 B/A 不行)

我的.htaccess 文件中有代码

重写引擎开启

1 变量案例

RewriteRule ^/Location-([^/]+)/$ /index.php?Location=$1 [L]

RewriteRule ^/Education-([^/]+)/$ /index.php?Education=$1 [L]

(...)

2个变量案例

(...)

4个变量案例

RewriteRule ^/Location-([^/]+)/Education-([^/]+)/Sex-([^/]+)/Interest-([^/]+)/$ /index.php?Location=$1&Education=$2&Sex=$3&Interest=$4 [L]

如果我有 8 个变量,这会变得非常长。

有没有更聪明的方法来实现上述目标?可能使用 [C] - 链或 [N] - 下一个? (URL 变量的顺序很重要)

提前致谢

【问题讨论】:

    标签: php .htaccess friendly-url


    【解决方案1】:

    试试这个:

    RewriteRule ^/([^-]+)-([^/]+)/$ /index.php?$1=$2 [L]
    RewriteRule ^/([^-]+)-([^/]+)/([^-]+)-([^/]+)/$ /index.php?$1=$2&$3=$4 [L]
    RewriteRule ^/([^-]+)-([^/]+)/([^-]+)-([^/]+)/([^-]+)-([^/]+)/$ /index.php?$1=$2&$3=$4&$5=$6 [L]
    RewriteRule ^/([^-]+)-([^/]+)/([^-]+)-([^/]+)/([^-]+)-([^/]+)/([^-]+)-([^/]+)/$ /index.php?$1=$2&$3=$4&$5=$6&$7=$8 [L]
    ...
    

    【讨论】:

    • 我的意思是“如何编写更智能(更短)的代码”。当用户选择少于 4 个标准时,您的单行代码不起作用。 - 404 错误。
    • @user706087 我无法从你的问题中提取这个。我编辑了我的答案。我希望这对你有帮助。
    • 其实这也无济于事。如果用户只浏览 E,你的 4 行代码将返回 404 错误。 (因为没有单独为 E 案例定义 RewriteRule)所以我的问题是,随着我添加更多搜索条件,这个简单的 RewriteRule 列表将呈指数增长。例如“如果我有 9 个搜索条件。如何在不编写数千个简单的 RewriteRule 代码的情况下实现上述目标?任何嵌套的更聪明的方式?” - 如果让您感到困惑,请对原始帖子表示抱歉。
    • @user706087 我已经编辑了我的答案。现在它将使用从 / 到 - 的所有内容作为键,使用从 - 到 / 的所有内容作为值。您可以在 htaccess 中只用 9 行代码轻松地将其扩展到 9 个条件。我希望这就是你要找的:-)
    • @user706087 有什么回应吗?有帮助吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-30
    • 1970-01-01
    • 1970-01-01
    • 2017-06-16
    • 2011-01-27
    • 1970-01-01
    相关资源
    最近更新 更多