Apache重写规则 - 路径样式

时间:2012-07-23 08:35:03

标签: apache mod-rewrite

我将从IIS世界转到Apache,并希望获得有关重写规则的一些帮助。

我想要这条相对路径:

/index.php?go=order&id=12345

被重写为:

/go/order/id/12345

此外,如果有更多参数,则应将它们转换为路径格式:

/index.php?go=order&id=12345&action=process

变为

/go/order/id/12345/action/process

我该如何做到这一点?感谢您的任何意见。

1 个答案:

答案 0 :(得分:1)

尝试将其放入vhost配置中:

RewriteEngine On

# Start converting query parameters to path
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /index\.php\?[^\ ]+
RewriteCond %{QUERY_STRING} ^([^=]+)=([^&]+)&?(.*)$
RewriteRule ^(.*)$ $1/%1/%2?%3 [L]

# done converting, remove index.php and redirect browser
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /index\.php\?[^\ ]+
RewriteCond %{QUERY_STRING} ^$
RewriteRule ^/index.php/(.*)$ /$1 [R=301,L]

# internally rewrite paths to query strings
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !^/index\.php
RewriteRule ^/([^/]+)/([^/]+)/?(.*) /$3?$1=$2 [L,QSA]

# No more path, rewrite to index.php
RewriteRule ^/$ /index.php [L]

如果您在浏览器中键入http://yourdomain.com/index.php?a=b&1=2&z=x之类的网址,这些规则就会如此,浏览器将重定向到http://yourdomain.com/a/b/1/2/z/x。当请求看起来整洁的URL时,第二组规则会在内部将其重写回/index.php?a=b&1=2&z=x。如果要将这些规则放在htaccess文件中(在文档根目录中),则需要删除RewriteRule中的所有主斜杠。因此,^/必须在最后3条规则中^

请注意,如果您只是转到http://yourdomain.com/index.php,没有查询字符串,则不会重写任何内容。

相关问题