有条件地将目录结构URL重定向到html文件

时间:2014-02-17 01:45:53

标签: regex apache .htaccess mod-rewrite

我的目标是将http://mydomain.com/somename之类的任何网址重定向到http://mydomain.com/somename.htmlhttp://mydomain.com/name1http://mydomain.com/name2除外。对于这两个网址,我希望将其重定向到{{1} }(或name2等)。如果后面两个在URL中有两个或三个以上的目录(即http://mydomain.com/main.php?g1=name1),我希望将它们添加为单独的GET值,例如http://mydomain.com/name1/val2/val3。我希望浏览器继续显示目录路径,而不是http://mydomain.com/main.php?g1=name1&g2=val2&g3=val3

以下是我的失败尝试。我怎么能做到这一点?谢谢

http://mydomain.com/somename.html

1 个答案:

答案 0 :(得分:1)

在大多数地方你都有正确的想法,但你需要改变规则的顺序,以便在不太具体的东西之前匹配更具体的东西。通常,我允许通过/在下面的规则中跟踪/?。如果您不允许尾随/匹配,请从最后删除。

RewriteEngine on
RewriteBase /

# This should be fine as you have it....
## If the request is for a valid directory, file, or link, don't do anything
RewriteCond %{REQUEST_FILENAME} -d [OR]
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -l
RewriteRule ^ - [L]

# Reverse your rule order here.
# First match name1|name2 with an optional trailing /
# but nothing else following...
RewriteRule ^(name1|name2)/?$ main.php?g1=$1 [L,QSA]
# Two additional dirs
RewriteRule ^(name1|name2)/([^/]+)/([^/]+)/?$ main.php?g1=$1&g2=$2&g3=$3 [L,QSA]
# Three additional dirs
RewriteRule ^(name1|name2)/([^/]+)/([^/]+)/([^/]+)/?$ main.php?g1=$1&g2=$2&g3=$3&g4=$4 [L,QSA]

# Last, do the generic rule to rewrite to .html
# using [^.]+ to match anything not including a .
# You could be more specific with something like [a-z]+ if that
# corresponds to your expected input
RewriteRule ^([^.]+)$ $1.html [L,QSA]

如果您想在条件中检查URI不是name1, name2,请使用隐含的[AND]

RewriteCond %{REQUEST_URI} !/name1
RewriteCond %{REQUEST_URI} !/name2
RewriteRule ^([^.]+)$ $1.html [L,QSA]