2013-07-16 63 views
0

代码中的3条评论相当准确地解释了我想实现的目标。无法使htaccess重定向www到非www网站

<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实现它,所以如果你也可以发现问题在哪里,这将是非常有益的

+0

我会把WWW。先去除。请记住,RewriteConds是正则表达式的,所以要逃避。'(\。)'。你可以进入任何情况下你添加尾随/之后**但实际的目录?你不应该那样做。只有目录应该有/。 –

回答

0

我面临与火狐存储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 
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] 

我不知道最后的规则。

+0

主要问题来自第一位,而不是尾随斜线。我结束了在PHP中使用斜杠并使用.htaccess实现了另外两个斜线 –

相关问题