用于多个RewriteRules的RewriteCond

时间:2018-07-27 13:32:05

标签: .htaccess mod-rewrite

当前,我有以下.htaccess文件。

RewriteEngine on

RewriteCond %{HTTP_HOST} ^([a-z-]+)\.example\.com$ [NC]
RewriteCond %1 !^(javascript|css|images)$ [NC]
RewriteRule ^ index.php?file=index [NC,L,QSA]

RewriteCond %{HTTP_HOST} ^([a-z-]+)\.example\.com$ [NC]
RewriteCond %1 !^(javascript|css|images)$ [NC]
RewriteRule ^language/?$ index.php?file=language [NC,L,QSA]

RewriteCond %{HTTP_HOST} ^([a-z-]+)\.example\.com$ [NC]
RewriteCond %1 !^(javascript|css|images)$ [NC]
RewriteRule ^about-us/?$ index.php?file=about_us [NC,L,QSA]

如您所见,我必须为每个RewriteRule复制以下两行:

RewriteCond %{HTTP_HOST} ^([a-z-]+)\.example\.com$ [NC]
RewriteCond %1 !^(javascript|css|images)$ [NC]

这可行,但是我想知道是否有更好的解决方案?

我想要什么?

例如,当用户访问http:// {subdomain-here} .example.com / about-us时,必须显示页面index.php?file = about_us。对于每个子域,对于子域javascript,css和图像,除外

编辑1:如果访问者访问http://javascript.example.com/about-us,则浏览器应显示404错误。

编辑2:“通用”正则表达式(例如(。*))将不起作用,因为URL中的文件名并不总是与原始文件名相同。 http://subdomain.example.com/about-us应该指向index.php?file = about_us(请参阅_),而不要指向index.php?file = about-us。

2 个答案:

答案 0 :(得分:1)

您可以应用相反的逻辑

RewriteEngine on

# Don't touch anything when it comes to those 3 subdomains
RewriteCond %{HTTP_HOST} ^(?:javascript|css|images)\.example\.com$ [NC]
RewriteRule ^ - [L]

# If we reach this part, this means we're not in the 3 subdomains restriction

RewriteRule ^$ /index.php?file=index [NC,L]
RewriteRule ^language$ /index.php?file=language [NC,L]
RewriteRule ^about-us$ /index.php?file=about_us [NC,L]

您可以看到它等同于

if subdomain in (javascript, css, images)
  return

do something here for other subdomains

答案 1 :(得分:0)

您可以使用

RewriteEngine on

RewriteCond %{HTTP_HOST} ^([a-z-]+)\.example\.com$ [NC]
RewriteCond %1 !^(javascript|css|images)$ [NC]
RewriteRule ^(.*) index.php?file=$1 [NC,L,QSA]

或以下 :

RewriteEngine on

RewriteCond %{HTTP_HOST} !^(javascript|css|images) [NC]
RewriteRule ^(.*) index.php?file=$1 [NC,L,QSA]