htaccess重定向URL中的用户名而忽略目录

时间:2017-04-03 23:28:04

标签: apache .htaccess redirect mod-rewrite

我有一个复杂的.htaccess重定向问题。我正在尝试将旧网站附属机构重定向到第二个域,其结构可以是以下内容:

  1. username.domain.com重定向到seconddomain.com/username
  2. domain.com/username重定向到seconddomain.com/username
  3. www.domain.com需要重定向到domain.com,而不是secondomain.com/www
  4. domain.com和子目录(即css,js,img)不会被重定向
  5. 以下是我当前的.htaccess但是它错误地将www.domain.com重定向到seconddomain.com/www并错误地将链接重定向到js,css和img目录到了seconddomain:

    <IfModule mod_rewrite.c>
    
    Options +FollowSymLinks 
    
    RewriteEngine on
    RewriteOptions inherit
    
    RewriteCond %{HTTP_HOST} ^www\.domain\.com/*$
    RewriteRule ^(.*)$ https://seconddomain.com/$1/ [R=301,L]
    
    RewriteCond %{HTTP_HOST} ^(.*)\.domain\.com
    RewriteRule ^(.*)$ https://seconddomain.com/%1/ [R=301,L]
    
    RewriteCond %{HTTP_HOST} .*
    RewriteRule ^(.+)$ https://seconddomain.com/$1/ [R=301,L]
    
    </IfModule>
    

2 个答案:

答案 0 :(得分:0)

您列出了四个案例:

  1. username.example.com重定向到secondexample.com/username
  2. example.com/username重定向到secondexample.com/username
  3. www.example.com需要重定向到example.com,而不是 secondexample.com/www
  4. example.com和子目录(即css,js,img)没有得到 重定向
  5. 以下情况应处理这些情况:

    RewriteEngine on
    
    #should handle case 3) www.example.com needs to redirect to example.com, not secondexample.com/www
    RewriteCond %{HTTP_HOST} ^www\.example\.com$
    RewriteRule ^(.*)$ https://example.com/$1/ [R=301,END]
    
    #should handle case 1) username.example.com redirects to secondexample.com/username
    RewriteCond %{HTTP_HOST} !^www\.example\.com$
    RewriteCond %{HTTP_HOST} ^(.+)\.example\.com
    RewriteRule ^(.*)$ https://secondexample.com/%1/ [R=301,L]
    
    #should handle case 2) example.com/username redirects to secondexample.com/username
    #and 4) example.com and subdirectories (i.e. css, js, img) don't get redirected
    RewriteCond %{HTTP_HOST} ^example\.com
    RewriteCond %{REQUEST_URI} !^/(css|js|img|<add-more-if-needed>)
    RewriteCond %{REQUEST_URI} !^/$
    RewriteRule ^(.*)$ https://secondexample.com/$1/ [R=301,L]
    

答案 1 :(得分:0)

所以这就是我现在所拥有的。一切正常,除了example.com重定向到secondexample.com。 www.example.com实际上重定向到example.com/test/,因为我已将测试添加到我忽略的子目录中。

RewriteEngine on

#should handle case 3) www.example.com needs to redirect to example.com, not 
#secondexample.com/www
RewriteCond %{HTTP_HOST} ^www\.example\.com$
RewriteRule ^(.*)$ http://example.com/test/$1/ [R=301,L]

#should handle case 1) username.example.com redirects to 
#secondexample.com/username
RewriteCond %{HTTP_HOST} !^www\.example\.com$
RewriteCond %{HTTP_HOST} ^(.+)\.example\.com
RewriteRule ^(.*)$ https://secondexample.com/%1/ [R=301,L]

#should handle case 2) example.com/username redirects to 
#secondexample.com/username
#and 4) example.com and subdirectories (i.e. css, js, img) don't get 
#redirected
RewriteCond %{HTTP_HOST} ^example\.com
RewriteCond %{REQUEST_URI} !^/(css|scripts|img|video)
RewriteRule ^(.*)$ https://secondexample.com/$1/ [R=301,L]