301将非www重定向到www

时间:2017-11-17 16:25:21

标签: apache .htaccess mod-rewrite

我正在尝试将所有non-www重定向到我网站上的www!我的SSL已配置为将所有http重定向到https,但我发现的所有内容仅对我有效!

如果我输入mysite.com/en/articles/12/how-to-code,例如我被重定向到           www.mysite.com/index.php应该是www.mysite.com/en/articles/12/how-to-code

我已尝试过这个SO question的解决方案,我知道这个问题可能会重复,但其他解决方案对我没用!我正在使用apache2。

这是/ public文件夹中的.htaccess

<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews
    </IfModule>

    RewriteEngine On

    # Redirect Trailing Slashes If Not A Folder...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)/$ /$1 [L,R=301]

    # Handle Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]

    # Handle Authorization Header
    RewriteCond %{HTTP:Authorization} .
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

    # Redirect to www
    RewriteCond %{HTTP_HOST} ^[^.]+\.[^.]+$
    RewriteCond %{HTTPS}s ^on(s)|
    RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
</IfModule>

提前致谢

1 个答案:

答案 0 :(得分:6)

更改顺序,并在重写前重定向:

<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews
    </IfModule>

    RewriteEngine On

    # Redirect Trailing Slashes If Not A Folder...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)/$ /$1 [L,R=301]

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

    # Handle Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]

    # Handle Authorization Header
    RewriteCond %{HTTP:Authorization} .
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
</IfModule>

因为如果在重写URL后重定向,这是将为重定向请求修改和返回的最后一个版本。