2012-07-23 127 views
0

我从IIS世界来到Apache,希望对重写规则有所帮助。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

尝试把这个在你的虚拟主机配置:

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] 

这些规则将使它所以如果你像在浏览器中​​一个URL类型,浏览器将重定向到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,而没有查询字符串,则不会重写任何内容。

+0

太棒了!现在我们如何检查给定的路径是不是现有的目录或文件?静态资源未被加载。 – Nirmal 2012-07-29 08:04:22

+0

@Nirmal请参阅编辑,需要有'!-f'和'!-d'检查 – 2012-07-29 08:07:35

+0

感谢Jon!你今天教给我一些新东西! :) – Nirmal 2012-07-29 08:22:15