简体   繁体   English

从www到非www的重定向不起作用

[英]Redirection from www to non-www doesn't work

I am trying to set a redirection from www to non-www page. 我正在尝试设置从www到非www页面的重定向。 I found plenty of instruction but I am missing something. 我找到了很多指导,但我遗漏了一些东西。 Tracerout from www and non-www is identical and it's hitting my server so the DNS is save. 来自www和非www的Tracerout是相同的,它正在命中我的服务器,所以DNS保存。

Here is my apache2 conf file: 这是我的apache2 conf文件:

<VirtualHost *:80>

    ServerAdmin webmaster@localhost
    ServerName mypage.com
    ServerAlias www.mypage.com
    DocumentRoot /var/www/mypage

    <Directory />
            Options FollowSymLinks
            AllowOverride All
    </Directory>

    <Directory /var/www/mypage>
            Options Indexes FollowSymLinks MultiViews
            AllowOverride All
            Order allow,deny
            allow from all
    </Directory>

    ErrorLog ${APACHE_LOG_DIR}/error.log

    CustomLog ${APACHE_LOG_DIR}/access.log combined
    </VirtualHost>

and here is my .htaccess file: 这是我的.htaccess文件:

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ http://%1/$1 [R=301,L]
</IfModule>

Can anyone see what am I missing? 任何人都可以看到我错过了什么?

The reason your rule redirecting www to non-www probably isn't working is because it occurs after other rules with the L flag (which of course means to stop processing the rewrite rules). 您的规则重定向到非www的规则可能不起作用的原因是因为它发生在带有L标志的其他规则之后(这当然意味着停止处理重写规则)。 You might consider the following configuration, which puts that particular part first: 您可以考虑以下配置,将该特定部分放在第一位:

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
    RewriteRule ^ http://%1%{REQUEST_URI} [R=301,L]
    RewriteBase /
    RewriteRule ^index\.php$ - [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^ /index.php [L]
</IfModule>

I want to note a couple things here. 我想在这里注意几件事。

  • The RewriteBase directive is kind of unnecessary here, unless that htaccess file isn't in the document root. 除非htaccess文件不在文档根目录中,否则RewriteBase指令在这里是不必要的。
  • The RewriteRule for non-www can use the %{REQUEST_URI} variable, and simply rewrite the entire request. 非www的RewriteRule可以使用%{REQUEST_URI}变量,只需重写整个请求即可。
  • Assuming you meant to rewrite the entire URI to /index.php on the last rule, you'd use the ^ character for that. 假设您打算在最后一条规则/index.php整个URI重写为/index.php ,那么您将使用^字符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM