使用mod_rewrite更改url路径

时间:2010-11-13 00:01:39

标签: apache .htaccess mod-rewrite

是否可以在URL中使文件夹透明,如下例所示: example.com/test/ 变成 example.com /

使用mod_rewrite?

我喜欢组织文件夹,但我想要一个干净的网址。

1 个答案:

答案 0 :(得分:3)

你可以通过mod_rewrite在你的根文件夹的.htaccess文件中放置这样的东西来实现这个目的:

RewriteEngine on

# the first condition is for avoiding an infinite loop
RewriteCond %{REQUEST_URI} !^/test/.*
RewriteRule ^(.*)$  /test/$1

这将重定向到/test/ /所请求的所有网页/文件。

如果您只想重定向某些文件,请使用更具体的规则:

RewriteEngine on

# the condition is for avoiding an infinite loop
RewriteCond %{REQUEST_URI} !^/test/.*
# redirecting only images files and files that start with "doc"
RewriteRule ^(.*\.(jpg|png|gif))$  test/$1 [L]
RewriteRule ^(doc.*)$  test/$1 [L]

或者如果您想使用不同的文件夹:

RewriteEngine on

# the condition is for avoiding an infinite loop
RewriteCond %{REQUEST_URI} !^/images/.*
RewriteCond %{REQUEST_URI} !^/docs/.*
# redirecting only images files and files that start with "doc"
RewriteRule ^(.*\.(jpg|png|gif))$  images/$1 [L]
RewriteRule ^(doc.*)$  docs/$1 [L]