Redirect Non-WWW to WWW URLs

前端 未结 6 2051
盖世英雄少女心
盖世英雄少女心 2020-12-09 06:11

When people access my domain it is redirected to http://www.mydomain.com/en/index.php using php code.I added the following code in .htaccess

RewriteEngine on         


        
相关标签:
6条回答
  • 2020-12-09 06:43

    I think you want to redirect the user instead of rewriting the URL, in that case use Redirect or 'RedirectMatch` directive. http://httpd.apache.org/docs/2.3/rewrite/remapping.html#old-to-new-extern

    0 讨论(0)
  • 2020-12-09 06:46
    $protocol = (@$_SERVER["HTTPS"] == "on") ? "https://" : "http://";
    
    if (substr($_SERVER['HTTP_HOST'], 0, 4) !== 'www.') {
        header('Location: '.$protocol.'www.'.$_SERVER['HTTP_HOST'].'/'.$_SERVER['REQUEST_URI']);
        exit;
    }
    

    in php

    0 讨论(0)
  • 2020-12-09 06:48

    Add RewriteEngine On before RewriteCond to enable your rewrite rules:

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

    And if you have https:

    RewriteEngine On
    
    RewriteRule .? - [E=PROTO:http]
    
    RewriteCond %{HTTPS} =on
    RewriteRule .? - [E=PROTO:https]
    
    RewriteEngine On
    RewriteCond %{HTTP_HOST} !^www\.
    RewriteRule ^(.*)$  %{ENV:PROTO}://www.%{HTTP_HOST}/$1 [R=301,L]
    
    0 讨论(0)
  • 2020-12-09 06:49
    <?php
    $protocol = (@$_SERVER["HTTPS"] == "on") ? "https://" : "http://";
    if (substr($_SERVER['HTTP_HOST'], 0, 4) !== 'www.') {
        header('Location: '.$protocol.'www.'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
        exit;
    }
    ?>
    

    Working Properly

    0 讨论(0)
  • 2020-12-09 06:50
    Redirect 301 /pages/abc-123.html http://www.mydomain.com/en/page-a1/abc.php
    
    <IfModule mod_rewrite.c>
    Options +FollowSymlinks
    RewriteEngine on
    
    # mydomain.com -> www.mydomain.com
    RewriteCond %{HTTP_HOST} ^mydomain.com
    RewriteRule ^(.*)$ http://www.mydomain.com/$1 [R=301,L]
    </IfModule>
    
    0 讨论(0)
  • 2020-12-09 07:00

    I'm not sure how to do it through .htaccess, but I do it with PHP code myself within my config.php which is loaded for every file.

    if(substr($_SERVER['SERVER_NAME'],0,4) != "www." && $_SERVER['SERVER_NAME'] != 'localhost')
        header('Location: http://www.'.$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI']);
    

    EDIT: @genesis, you are correct I forgot about https

    Change

    header('Location: http://www.'.$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI']);
    

    to

    header('Location: '.
           (@$_SERVER['HTTPS'] == 'on' ? 'https://' : 'http://').
           'www.'.$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI']);
    
    0 讨论(0)
提交回复
热议问题