apache 将非WWW重定向到WWW URL

kzipqqlq  于 12个月前  发布在  Apache
关注(0)|答案(6)|浏览(116)

当人们访问我的域名时,它会使用php代码重定向到http://www.mydomain.com/en/index.php

RewriteEngine on
Options +FollowSymlinks

RewriteBase /
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]
RedirectPermanent /pages/abc-123.html http://www.mydomain.com/en/page-a1/abc.php

将人们从非www重定向到www
用户仍然可以通过输入http://mydomain.com/en/page-a1/abc.phphttp://www.mydomain.com/en/page-a1/abc.php URL来访问
有没有人知道的方法完全重定向到http://www.mydomain.com/en/page-a1/abc.php,即使用户键入http://www.mydomain.com/en/page-a1/abc.php,并禁止访问没有www的网址。

hgtggwj0

hgtggwj01#

$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;
}

在php中

ie3xauqp

ie3xauqp2#

<?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;
}
?>

正常工作

fivyi3re

fivyi3re3#

我不知道如何通过.htaccess来实现,但我自己在config.php中使用PHP代码来实现,config.php为每个文件加载。

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

编辑:@genesis,你是对的,我忘记了https

变化

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

header('Location: '.
       (@$_SERVER['HTTPS'] == 'on' ? 'https://' : 'http://').
       'www.'.$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI']);
5n0oy7gb

5n0oy7gb4#

RewriteCond之前添加RewriteEngine On以启用重写规则:

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

如果你有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]
cuxqih21

cuxqih215#

我认为你想重定向用户而不是重写URL,在这种情况下使用Redirect或'RedirectMatch'指令。http://httpd.apache.org/docs/2.3/rewrite/remapping.html#old-to-new-extern

92vpleto

92vpleto6#

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>

相关问题