simple mod_rewrite redirects

浪子不回头ぞ 提交于 2019-12-24 13:40:21

问题


After a lot of research and some help, I managed to learn a bit of how mod rewrite works... Can someone tell me what's wrong with my code bellow?

######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]

Thanks!

Also, what's the difference between:

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

and

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

回答1:


Try this .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]



回答2:


Based off our previous conversation. You can also combine the www and IP rule. It only needs to check if www is not there.

######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

This is other way.



来源:https://stackoverflow.com/questions/28820476/simple-mod-rewrite-redirects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!