mod_rewrite遇到/ product /?id = {xyz} to / product / {xyz}

时间:2013-04-18 18:30:41

标签: .htaccess mod-rewrite

我的尝试:

RewriteCond %{QUERY_STRING}     ^id=(.*)$    [NC]
RewriteRule ^/product$       /product/%1      [NC,L,R=301]

我想将此规则仅应用于/product//supplier/目录。它们都是第一级子目录。

注意:product/?id={xxx}实际上是product/index.php?id={xxx}。 Apache隐藏了我的扩展和索引。只是想指出这一点。

我的product/index.php处理给定的参数并确定它应显示的页面:

的index.php

if ( isset( $_GET['id'] ) && !empty( $_GET['id'] ) ) {
   //html for individual page e.g. /product/?id=foo
   //e.g. <h1><?= $_GET['id'] ?> Page</h1>
} else {
   //html for product list e.g. /product/ (no parameters)
}

1 个答案:

答案 0 :(得分:1)

在根目录下的一个.htaccess文件中尝试:

Options +FollowSymlinks -MultiViews
RewriteEngine On
RewriteBase /
RewriteCond %{QUERY_STRING} id=(.+)          [NC]
RewriteRule ^(product|supplier)/?$   /$1/%1? [NC,L,R=301]

在.htaccess文件中,规则中的URI路径测试没有前导斜杠(^/product),因此正则表达式也不能拥有它。 trailng ?删除传入的查询。

如果要将规则集放在Apache主配置文件中,则应保留前导斜杠:^/(product|supplier)/?$

更新

显示所需的网址,但仍然可以从原始网址获取数据。

请求:/product/?id=parameter

Options +FollowSymlinks -MultiViews
RewriteEngine On
RewriteBase /

RewriteCond %{THE_REQUEST} ^(GET|HEAD)\s/(product|supplier)/\?id=([^\s]+) [NC]
# Strip the query and redirect permanently
RewriteRule  ^(product|supplier)  /$1/%3?   [R=301,L,NC]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{QUERY_STRING} ^$
# Map internally to the original request
RewriteRule  ^(product|supplier)/([^/]+)/?  /$1/?id=$2  [L,NC]

另一种选择是直接在请求中使用“漂亮”的URL:

/product/parameter

请求/product/?id=parameter
Options +FollowSymlinks -MultiViews
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{QUERY_STRING} ^$
RewriteRule  ^(product|supplier)/([^/]+)/?  /$1/?id=$2  [L,NC]