将非www重定向到www。等效但允许一个REQUEST_URI正则表达式匹配?

时间:2015-04-10 20:21:15

标签: .htaccess mod-rewrite

RewriteCond %{HTTP_HOST} !^www\. [NC] 
RewriteCond %{REQUEST_URI} !^.+?games/.+?\.jpg$ [NC] #if does not match then proceed with redirect...
RewriteRule ^(.*)$ http://www.example.com/$1 [R=301,L]

RewriteRule ^.+?games/(.+?)\.jpg$ index.php?g=$1 [L] #will only get to this point if not starting with www.

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d 
RewriteRule .* index.php [L]

以上代码不起作用,我做错了什么?

1 个答案:

答案 0 :(得分:0)

问题是您使用的REQUEST_URI变量由于您的上一条规则而更改为/index.php,而当mod_rewrite再次运行时,您的第一条规则很乐意在网址中添加www

您应该使用THE_REQUEST变量,THE_REQUEST变量表示Apache从您的浏览器收到的原始请求,并且在执行某些重写规则后它不会被覆盖。

RewriteCond %{HTTP_HOST} !^www\. [NC] 
RewriteCond %{THE_REQUEST} !games/.+?\.jpg [NC]
RewriteRule ^(.*)$ http://www.example.com/$1 [R=301,L]

RewriteRule ^.+?games/(.+?)\.jpg$ index.php?g=$1 [L,QSA]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d 
RewriteRule .* index.php [L]