简单的mod_rewrite重定向

时间:2015-03-02 22:15:32

标签: apache .htaccess mod-rewrite

经过大量的研究和一些帮助后,我设法了解了mod重写的工作原理......有人能告诉我我的代码有什么问题吗?

######redirect all static files to the static domain
RewriteCond %{REQUEST_URI} ^/(.+)\.(gif|png|jpg|jpeg|jfif|bmp|css|js)$ [NC]
RewriteRule ^(.*)$ http://static.example.com/$1 [R=301,L]

######redirect naked to www
RewriteCond %{HTTP_HOST} ^example.com$ [NC]
RewriteRule (.*) http://www.example.com/$1 [R=301,L]

######redirect IP to www
RewriteCond %{HTTP_HOST} ^100\.100\.100\.100$
RewriteRule ^(.*)$ http://www.example.com/$1 [R=301,L]

######redirect all non static files from static domain (because that remains) to www
RewriteCond %{REQUEST_FILENAME} !\.(gif|png|jpg|jpeg|jfif|bmp|css|js)$ [NC]
RewriteRule ^(.*)$ http://www.example.com/$1 [R=301,L]

谢谢!

另外,区别是:

RewriteCond %{REQUEST_URI} !^/(.+)\.(gif|png|jpg|jpeg|jfif|bmp|css|js)$ [NC]

RewriteCond %{REQUEST_FILENAME} !\.(gif|png|jpg|jpeg|jfif|bmp|css|js)$ [NC]

2 个答案:

答案 0 :(得分:1)

试试这个.htaccess:

######redirect all static files to the static domain
RewriteCond %{HTTP_HOST} ^(www\.)?example\.com$ [NC]
RewriteRule \.(gif|png|jpe?g|jfif|bmp|css|js)$ http://static.example.com%{REQUEST_URI} [R=301,L,NC]

######redirect naked to www
RewriteCond %{HTTP_HOST} ^example\.com$ [NC,OR]
RewriteCond %{HTTP_HOST} ^100\.100\.100\.100$
RewriteRule ^ http://www.example.com%{REQUEST_URI} [R=301,L]

######redirect all non static files from static domain (because that remains) to www
RewriteCond %{HTTP_HOST} ^static\. [NC]
RewriteRule !\.(gif|png|jpe?g|jfif|bmp|css|js)$ http://www.example.com%{REQUEST_URI} [R=301,L,NC]

答案 1 :(得分:1)

基于我们之前的对话。您还可以合并wwwIP规则。它只需要检查www是否不存在。

######redirect naked to www or IP
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule (.*) http://www.example.com/$1 [R=301,L]

######redirect all static files to the static domain
RewriteCond %{HTTP_HOST} ^(www\.)?example\.com [NC] 
RewriteCond %{REQUEST_URI} ^/(.+)\.(gif|png|jpg|jpeg|jfif|bmp|css|js)$ [NC]
RewriteRule ^(.*)$ http://static.example.com/$1 [R=301,L]

######redirect all non static files from static domain (because that remains) to www
RewriteCond %{HTTP_HOST} ^images\.example\.com [NC]
RewriteCond %{REQUEST_URI} !^/(.+)\.(gif|png|jpg|jpeg|jfif|bmp|css|js)$ [NC]
RewriteRule ^(.*)$ http://www.example.com/$1 [L,R=301

这是另一种方式。

相关问题