apache 将非WWW重定向到WWW URL

kzipqqlq  于 2023-10-23  发布在  Apache
关注(0)|答案(6)|浏览(172)

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

  1. RewriteEngine on
  2. Options +FollowSymlinks
  3. RewriteBase /
  4. RewriteCond %{HTTP_HOST} !^www\.
  5. RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]
  6. 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#

  1. $protocol = (@$_SERVER["HTTPS"] == "on") ? "https://" : "http://";
  2. if (substr($_SERVER['HTTP_HOST'], 0, 4) !== 'www.') {
  3. header('Location: '.$protocol.'www.'.$_SERVER['HTTP_HOST'].'/'.$_SERVER['REQUEST_URI']);
  4. exit;
  5. }

在php中

ie3xauqp

ie3xauqp2#

  1. <?php
  2. $protocol = (@$_SERVER["HTTPS"] == "on") ? "https://" : "http://";
  3. if (substr($_SERVER['HTTP_HOST'], 0, 4) !== 'www.') {
  4. header('Location: '.$protocol.'www.'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
  5. exit;
  6. }
  7. ?>

正常工作

fivyi3re

fivyi3re3#

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

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

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

变化

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

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

5n0oy7gb4#

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

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

如果你有https:

  1. RewriteEngine On
  2. RewriteRule .? - [E=PROTO:http]
  3. RewriteCond %{HTTPS} =on
  4. RewriteRule .? - [E=PROTO:https]
  5. RewriteEngine On
  6. RewriteCond %{HTTP_HOST} !^www\.
  7. 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#

  1. Redirect 301 /pages/abc-123.html http://www.mydomain.com/en/page-a1/abc.php
  2. <IfModule mod_rewrite.c>
  3. Options +FollowSymlinks
  4. RewriteEngine on
  5. # mydomain.com -> www.mydomain.com
  6. RewriteCond %{HTTP_HOST} ^mydomain.com
  7. RewriteRule ^(.*)$ http://www.mydomain.com/$1 [R=301,L]
  8. </IfModule>

相关问题