【问题标题】:.htaccess Redirect non-WWW to WWW preserving URI string.htaccess 将非 WWW 重定向到 WWW 保留 URI 字符串
【发布时间】:2010-12-13 17:53:34
【问题描述】:

我正在运行 CodeIgniter 平台,它使用 .htaccess 来接受类似的 URL

http://www.mysite.com/controller/function/argument

我目前使用一些 .htaccess 重写,即(简化):

RewriteEngine On
RewriteCond %{REQUEST_URI} !^(/index\.php|/images|/assets)
RewriteRule ^(.*)$ /index.php/$1 [L]

我想添加一个重写规则,将所有非 www 请求重定向到 www。我还希望域名后面的 URI 字符串在重定向中保持不变。例如,如果用户请求http://mysite.com/controller/function/argument,我希望.htaccess 文件在浏览器中将请求重写为http://www.mysite.com/controller/function/argument,然后处理该请求。

【问题讨论】:

    标签: php apache .htaccess mod-rewrite codeigniter


    【解决方案1】:

    我遇到了类似的问题,这个 .htaccess 对我有用

    RewriteEngine On                           
    
    #This bit rewrites your host name to include www
    RewriteCond %{HTTP_HOST} !^www\.example\.com [NC]
    RewriteRule ^(.*)$ http://www.example.com/$1 [R=301,NC,L]
    
    #This bit does the codeigniter magic
    RewriteCond %{REQUEST_FILENAME} !-f  
    RewriteCond %{REQUEST_FILENAME} !-d  
    RewriteRule ^(.*)$ /index.php/$1 [L]
    

    【讨论】:

    • 它正在工作。如果我想添加除了 blog.example.com 没有重定向到 www 的规则怎么办?
    • 试试RewriteCond %{HTTP_HOST} !^(www|blog)\.example\.com [NC]
    【解决方案2】:

    应该是这样的:

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

    【讨论】:

    • 这不会干扰我的第二个 RewriteRule 对吧?我理解你的 RewriteCond,我不想应用我已有的规则。
    • 如果将我的添加为第一个,则只有在主机不是 www.mysite.com 时才会激活。激活的话会有重定向HTTP,第二次HTTP查询满足条件会激活自己的重写
    • @Steven Xu,RewriteConds 仅适用于下一个直接的 RewriteRule。
    【解决方案3】:

    如果您使用的是 apache 2.4,您可以使用以下简单重定向:

    <if "%{HTTP_HOST} =='example.com'">
    Redirect / http://www.example.com/
    </if>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-11-16
      • 2011-04-12
      • 2015-12-31
      • 1970-01-01
      • 1970-01-01
      • 2011-09-25
      • 1970-01-01
      相关资源
      最近更新 更多