【问题标题】:Cannot make htaccess redirect www to non-www无法使 htaccess 将 www 重定向到非 www
【发布时间】:2013-07-17 06:05:32
【问题描述】:

代码中的 3 个 cmets 相当准确地解释了我想要实现的目标。

<IfModule mod_rewrite.c>
RewriteEngine On

# Change secretdiary.org/index.php?url=URL to secretdiary.org/URL on the browser's url
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?url=$1 [PT,L]

# Redirect http://www.secretdiary.org/ to http://secretdiary.org/
RewriteCond %{HTTP_HOST} !^secretdiary.org$ [NC]
RewriteRule ^(.*)$ http://secretdiary.org/$1 [L,R=301]

# Add trailing slash / if there's none
RewriteCond %{REQUEST_URI} !(/$|\.) 
RewriteRule (.*) %{REQUEST_URI}/ [R=301,L]
</IfModule>

但是,我发现了一些问题,我认为它们来自于将条件放在一起。当我输入 www.secretdiary.org/about 时,它会(在浏览器中显示)到 secretdiary.org/index.php?url=about,删除 www 但忽略第一条规则。切换顺序根本没有帮助,也没有弄乱RewriteBase。但是,如果我在没有www 的情况下正常输入,则uri 会正常显示,secretdiary.org/about,无需任何重写。 为什么会这样,我该如何解决?

此外,我已经关注 this answerthis other 尝试在 uri 丢失时自动添加尾部斜杠。我可以用 PHP (if (substr($_GET['url'], -1) != "/") header("Location: " . htmlspecialchars($_GET['url']) . '/');) 实现它,但现在让我感到困扰的是我无法用 .htaccess 实现它,所以如果你也能发现这里的问题在哪里,那将非常有帮助。

【问题讨论】:

  • 我会把 www.先去除。请记住,RewriteConds 是正则表达式,因此请转义 . 的 (\.)。你能遇到在任何实际目录之后添加尾随/的情况吗?你不应该那样做。只有目录应该有 /。

标签: apache .htaccess mod-rewrite rewrite


【解决方案1】:

试试这个 .htaccess 代码:

RewriteEngine On

# Change secretdiary.org/index.php?url=URL to secretdiary.org/URL on the browser's url
RewriteCond %{HTTP_HOST} ^secretdiary.org$ [NC]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?url=$1 [L]

# Redirect http://www.secretdiary.org/ to http://secretdiary.org/
RewriteCond %{HTTP_HOST} !^secretdiary.org$ [NC]
RewriteRule ^(.*)$ http://secretdiary.org/$1 [R=301]

# Add trailing slash / if there's none
RewriteRule ^([^/]*)[^/]$ $1/ [R=301,L]

我不确定最后一条规则。

【讨论】:

  • 主要问题来自第一位,而不是尾部斜杠。我用 .htaccess 结束了在 PHP 和另外两个中实现斜线
【解决方案2】:

我面临的主要问题是 Firefox 存储 301 重定向,这使得 .htaccess 中的更改“不起作用”。我删除了缓存,现在它运行良好,尽管我在 PHP 中添加了尾部斜杠以避免头痛。

.htaccess:

<IfModule mod_rewrite.c>
RewriteEngine On

# For some shady reason, this redirect should be first.
# Redirect http://www.secretdiary.org/ to http://secretdiary.org/
RewriteCond %{HTTP_HOST} !^secretdiary.org$ [NC]
RewriteRule ^(.*)$ http://secretdiary.org/$1 [L,R=301]

# Change secretdiary.org/index.php?url=URL to secretdiary.org/URL on the browser's url
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?url=$1 [PT,L]
</IfModule>

index.php:

<?php
// Redirect if there's no trailing slash
if (!empty($_GET['url']) && substr($_GET['url'], -1) != "/")
  {
  header ('HTTP/1.1 301 Moved Permanently');
  header ("Location: http://secretdiary.org/" . htmlspecialchars($_GET['url']) . "/");
  }

// The rest of the php

【讨论】:

    猜你喜欢
    • 2012-11-16
    • 2012-10-19
    • 1970-01-01
    • 2011-04-12
    • 2015-12-31
    • 1970-01-01
    • 1970-01-01
    • 2018-09-11
    • 1970-01-01
    相关资源
    最近更新 更多