用mod_rewrite重定向?

时间:2010-08-21 21:02:31

标签: .htaccess mod-rewrite

所以我有一个基于此参数search.php?state=AL查询某些数据的网页。

我要做的是在我的.htaccess文件中编写一条规则:

  1. website.com/state/AL翻译成search.php?state=AL
  2. 如果用户明确要求search.php?state=AL,请将其转换为/state/AL
  3. 我使用这个完成了第1步:

    RewriteRule ^state/([A-Za-z][A-Za-z]) /search.php?state=$1 [NC]

    如何完成第2步?我知道我必须使用[R, NC]来实际重写URL,但这就是我被困住的地方。

    编辑:不确定这是否重要但我的网站托管强迫我将RewriteBase /添加到.htaccess文件的顶部。

2 个答案:

答案 0 :(得分:2)

您只想在原始请求指向/search.php?state=网址的情况下执行重定向,如下所示:

RewriteEngine On

# Externally redirect /search.php?state=XX --> /state/XX
RewriteCond %{THE_REQUEST} ^[A-Z]+\s/search\.php\?state=([A-Z]{2}) [NC]
RewriteRule ^ http://%{HTTP_HOST}/state/%1? [R=301,L]

# Internally redirect /state/XX --> /search.php?state=XX
RewriteRule ^state/([A-Z]{2}) /search.php?state=$1 [NC]

答案 1 :(得分:0)

这样的事情可以解决问题:

RewriteRule ^state/([A-Za-z][A-Za-z]) /search.php?state=$1 [NC, L]
RewriteCond %{QUERY_STRING} state=([A-Za-z][A-Za-z])
RewriteRule ^search\.php$ /state/%1 [R=303, NC]