【问题标题】:MOD_REWRITE conditional redirectionMOD_REWRITE 条件重定向
【发布时间】:2012-11-18 16:24:55
【问题描述】:

我在使用 Apache Mod_Rewrite 模块时遇到问题,

我正在从 get 请求中检索三个变量

$country
$state
$location

本地重写url成功 例如网址

localhost/directory/country/state/location /*is redirected to*/
localhost/directory/result.php?c=country&s=state&l=location

我想做的是我要重定向

localhost/directory/country to localhost/directory/country.php?c=country

如果是

localhost/directory/country/state to localhost/directory/state.php?c=country&s=state

我正在使用以下 RewriteRule

RewriteEngine On
RewriteRule ^([^/]*)/([^/]*)/([^/]*)$ result.php?s=$1&d=$2&l=$3 [L]

如果我想只显示国家页面,我该如何重写国家和州,以及如果我只想显示国家页面..

非常感谢!! 请通过提供在线教程和其他参考资料来帮助我。

我非常有义务为您提供同样的服务.. :)

【问题讨论】:

  • 使用更少的占位符和您的其他/缩短的替换网址/参数复制该规则。

标签: php apache redirect rewrite


【解决方案1】:

您可以使用向下流动来识别网址是国家、州还是位置 类似于:

<IfModule mod_rewrite.c>
    Rewrite Engine On
    RewriteRule ^localhost/directory/([^/\.]+)/([^/\.]+)/([^/\.]+)/ localhost/directory/result.php?c=$1&s=$2&l=$3 [L]
    RewriteRule ^localhost/directory/([^/\.]+)/([^/\.]+)/ localhost/directory/state.php?c=$1&s=$2 [L]
    RewriteRule ^localhost/directory/([^/\.]+)/ localhost/directory/country.php?c=$1 [L]
</IfModule>

请注意我是如何首先从最长、最动态的 URL 开始的。如果您从最短的第一个开始,在您的情况下为 country,那么 URL_Rewrite 将首先接受 answer,而您将永远不会遇到其他两个重写。

虽然我发现在 PHP 解析方面更容易处理一个 php 页面上的所有动态 URL 流量,但在你的情况下,像 result.php 这样你就可以确定输出,而且你不必担心跳转围绕文件。

.htaccess

<IfModule mod_rewrite.c>
    Rewrite Engine On
    RewriteRule ^localhost/directory/([^/\.]+)/([^/\.]+)/([^/\.]+)/ localhost/directory/result.php?c=$1&s=$2&l=$3 [L]
    RewriteRule ^localhost/directory/([^/\.]+)/([^/\.]+)/ localhost/directory/result.php?c=$1&s=$2 [L]
    RewriteRule ^localhost/directory/([^/\.]+)/ localhost/directory/result.php?c=$1 [L]
</IfModule>

result.php

<?php
$location = isset($_GET['l']) ? $_GET['l'] : false;
$state    = isset($_GET['s']) ? $_GET['s'] : false;
$country  = isset($_GET['c']) ? $_GET['c'] : false;

// ...PARSE THE REST OF PHP based off of these variables
?>

【讨论】:

  • 非常感谢@samuel。我一定会利用您建议的文件变量解析概念...再次感谢
【解决方案2】:

我认为,你可以使用两条规则:

# localhost/directory/country
RewriteRule ^[^/]+/([^/]+)$  localhost/directory/country.php?c=$1 [L]

# localhost/directory/country/state
RewriteRule ^[^/]+/([^/]+)/([^/]+)$  localhost/directory/state.php?c=$1&s=$2 [L]

【讨论】:

    猜你喜欢
    • 2012-05-31
    • 2011-04-14
    • 1970-01-01
    • 2014-11-16
    • 2019-02-02
    • 2012-02-22
    • 2013-05-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多