我如何在https和http上强制使用www子域

时间:2010-12-02 12:52:07

标签: apache .htaccess mod-rewrite redirect

无论出于什么原因,我似乎无法做到这一点,我在这里和apache的网站上看了很多例子。我试图在EITHER http或https上强制使用www.domain.com而不是domain.com,但我并不想强迫https通过http。

以下代码似乎适用于所有https连接,但http不会重定向到www。

RewriteEngine On
RewriteCond %{HTTPS} on
RewriteCond %{HTTP_HOST} !^www\.domain\.com$ [NC]
RewriteRule ^ https://www.domain.com%{REQUEST_URI} [R=301]

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} !^www\.domain\.com$ [NC]
RewriteRule ^ http://www.domain.com%{REQUEST_URI} [R=301]

3 个答案:

答案 0 :(得分:1)

  1. 您不需要第二个RewriteEngine指令。这可能会也可能不会导致解析问题,导致第二组规则无效。要测试是否是这种情况,请尝试切换您拥有的两个块的顺序。
  2. 最好使用L来修改绝对最后的请求。因此,两次出现时都会[R=301]更改为[R=301,L]
  3. 在很大程度上,作为一种风格问题,我会考虑将RewriteRule指令更改为(适当时使用http或https):

    RewriteRule ^(.*)$ http://www.domain.com$1 [R=301,L,QSA]

答案 1 :(得分:1)

你的规则似乎没问题。您可以按如下方式组合它们:

RewriteCond %{HTTP_HOST} !^www\.example\.com$
RewriteCond %{HTTPS}s on(s)|
RewriteRule ^ http%1://www.example.com%{REQUEST_URI} [L,R=301]

另请注意额外的 L 标志,以便在应用此规则后停止重写过程。

答案 2 :(得分:0)

如果有人仍需要答案。使用另一个.htaccess。从这里获取指南,我找到它并且看起来不错:http://www.farinspace.com/codeigniter-htaccess-file/

<IfModule mod_rewrite.c>

    RewriteEngine On
    RewriteBase /

    ### Canonicalize codeigniter URLs

    # If your default controller is something other than
    # "welcome" you should probably change this
    RewriteRule ^(welcome(/index)?|index(\.php)?)/?$ / [L,R=301]
    RewriteRule ^(.*)/index/?$ $1 [L,R=301]

    # Removes trailing slashes (prevents SEO duplicate content issues)
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.+)/$ $1 [L,R=301]

    # Enforce www
    # If you have subdomains, you can add them to 
    # the list using the "|" (OR) regex operator
    RewriteCond %{HTTP_HOST} !^(www|subdomain) [NC]
    RewriteRule ^(.*)$ http://www.domain.tld/$1 [L,R=301]

    # Enforce NO www
    #RewriteCond %{HTTP_HOST} ^www [NC]
    #RewriteRule ^(.*)$ http://domain.tld/$1 [L,R=301]

    ###

    # Removes access to the system folder by users.
    # Additionally this will allow you to create a System.php controller,
    # previously this would not have been possible.
    # 'system' can be replaced if you have renamed your system folder.
    RewriteCond %{REQUEST_URI} ^system.*
    RewriteRule ^(.*)$ /index.php/$1 [L]

    # Checks to see if the user is attempting to access a valid file,
    # such as an image or css document, if this isn't true it sends the
    # request to index.php
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ index.php/$1 [L]

</IfModule>

<IfModule !mod_rewrite.c>

    # Without mod_rewrite, route 404's to the front controller
    ErrorDocument 404 /index.php

</IfModule>

请记住,一旦设置了CodeIgniter htaccess文件,您将需要进入“/system/application/config/config.php”,找到以下内容:

$config['index_page'] = "index.php";

并将其更改为:

$config['index_page'] = "";