mod_rewrite用于包含多个变量的URL

时间:2014-08-15 15:19:20

标签: .htaccess mod-rewrite

您好我正在尝试关注Mod_Rewrite for URL with multiple variables并对其进行编辑以适合我的网站,但我在互联网上搜索过一些问题并且找不到任何有用的内容

我正在尝试将example.com/editor/windows/chrome变成这个example.com?app=editor&os=windows&browser=chrome

有什么想法吗?

我当前的.htaccess文件:

# Various rewrite rules.
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([a-zA-Z0-9_-]+)/?$ index.php?app=$1 [QSA]
RewriteRule ^([a-zA-Z0-9_-]+)/([a-zA-Z0-9_-]+)/?$ index.php?app=$1&os=$2&browser=$3 [QSA]
</IfModule>

我可以让它分开工作到example.com/editor/windows但是不能让第三个包含浏览器

2 个答案:

答案 0 :(得分:2)

您的第三条规则不包含浏览器的捕获组。缺少此声明:

RewriteRule ^([a-zA-Z0-9_-]+)/([a-zA-Z0-9_-]+)/([a-zA-Z0-9_-]+)$ index.php?app=$1&os=$2&browser=$3 [QSA]

从上到下应用RewriteRules,直到找到[L]。因此,在您的问题中,两个规则都适用(可能会导致性能不佳)。

一个更干净的版本,

# Various rewrite rules.
<IfModule mod_rewrite.c>
RewriteEngine on

# don't rewrite URLs for existing files, directories or links
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d [OR]
RewriteCond %{REQUEST_FILENAME} -l
RewriteRule .* - [L]

# now match the URIs according to OP needs
# Redirect example.com/editor and example.com/editor/ to example.com/index.php?app=editor and stop after this rule
RewriteRule ^([a-zA-Z0-9_-]+)/?$ index.php?app=$1 [QSA,L]
# Redirect example.com/editor/windows and example.com/editor/windows/ to example.com/index.php?app=editor&os=windows and stop after this rule
RewriteRule ^([a-zA-Z0-9_-]+)/([a-zA-Z0-9_-]+)/?$ index.php?app=$1&os=$2 [QSA,L]
# Redirect example.com/editor/windows/chrome and example.com/editor/windows/chrome/ to example.com/index.php?app=editor&os=windows&browser=chrome and stop after this rule
RewriteRule ^([a-zA-Z0-9_-]+)/([a-zA-Z0-9_-]+)/([a-zA-Z0-9_-]+)/?$ index.php?app=$1&os=$2&browser=$3 [QSA,L]
</IfModule>

但是,最后三个RewriteRule规则也可以编译为一个:

RewriteRule ^([a-zA-Z0-9_-]+)(?:/([a-zA-Z0-9_-]+)(?:/([a-zA-Z0-9_-]+)))/?$ index.php?app=$1&os=$2&browser=$3 [QSA,L]

答案 1 :(得分:1)

只要您不介意留空$_GET[]个变量,就可以将其全部缩减为单个规则。同样不是您有2个条件可以检查!-f!-d。这些条件仅适用于紧随其后的规则,除非您复制条件,否则不会适用于任何其他规则。

所以你可以尝试:

# Various rewrite rules.
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([a-zA-Z0-9_-]+)(?:/([a-zA-Z0-9_-]+)|)(?:/([a-zA-Z0-9_-]+)|)/?$ index.php?app=$1&os=$2&browser=$3 [L,QSA]
</IfModule>