2011-01-07 55 views
1

我遇到了这种reg表达式的问题,我相信是正确的,但它不工作。 什么即时试图做的是含有的特定字符串像这样的URL重定向一堆:

http://www.example.com/**undesired-string**_another-stringhttp://www.example.com/**new-string**_another-string

http://www.example.com/folder/**undesired-string**/another-stringhttp://www.example.com/folder/**new-string**/another-string

HTACCESS重定向在网址中的字替换

所以我要在.htaccess验证码:

<IfModule mod_rewrite.c> 
    RewriteEngine On 
    RewriteBase/
    RewriteRule (.+)+(undesired-string)+(.+) $1new-string$2 [R=301,L] 
</IfModule> 

这应该将任何url中的任何不受欢迎的字符串替换为新字符串,但它会将不工作,为什么?

谢谢

回答

2

Marwen:在评论上述

<IfModule mod_rewrite.c> 
RewriteEngine On 
RewriteBase/

RewriteRule ^(.*)undesired-string(.*)$ yoursite.com/$1new-string$2 [R=301,L] 

RewriteCond %{REQUEST_FILENAME} !-f 
RewriteCond %{REQUEST_FILENAME} !-d 

RewriteRule ^(.*)$ index.php?/$1 [L] 

RewriteCond %{HTTP_HOST} !^www.yoursite.com$ [NC] 
RewriteRule ^(.*)$ yoursite.com//$1 [L,R=301] 
</IfModule> 

在你的“更新”的代码,你必须把它应用重写条件对不想要的字符串......所以,如果实际的文件或目录:试试这个有效它不会重写...

虽然这样做,但总是会用新字符串重写不想要的字符串 - 即使它的文件名...如果这很好或你想要什么,那么你所要做的将您的重写条件移至重写规则下方...

还..只是一个供参考。如果一切都在yoursite.com你不需要列出yoursite.com

yoursite.com/$1new-string$2 

只是需要

/$1new-string$2 

它执行同样的事情:重写到yoursite.com的基本目录

现在,如果他们从mysite.com到yoursite。COM那么你woulud要包括域名,因为你是跨域名重定向


编辑:您可能还需要使用:

[QSA,L,R=301] 

,而不是仅仅[L,R = 301]

1

你的正则表达式是不是真的正确。尝试:

RewriteRule ^(.*)undesired-string(.*)$ $1new-string$2 [R=301,L] 

或者,如果这不起作用,请尝试:

RewriteRule ^(.*)undesired-string(.*)$ http://yoursite.com/$1new-string$2 [R=301,L] 

说明: ^标记开始; $标志着结束;第一个(..)转到$ 1,第二个(..)转到$ 2等等; *是0或更多字符; +是1个或更多字符。

+0

谢谢你这是工作,但现在有另外一个问题,我有alreay样的RewriteRule ^(。*)$的index.php规则?/ $ 1,它overwritting你提到的一个,有没有什么办法来解决它 – Marwen 2011-01-07 20:45:26

+0

我想这应该工作,如果我的代码之前出现在您的代码... index.php?/ $ 1。应该首先处理重定向。 – Floern 2011-01-07 20:50:50

0

回答我自己的问题。 Laravel已经重新定向了后面的斜杠。问题是Laravel被安装到一个子目录中。我将子目录的位置添加到重定向。在这种情况下,我的位置是:“/ lumen/public /”。请参阅下面的固定htaccess。

<IfModule mod_rewrite.c> 
    <IfModule mod_negotiation.c> 
     Options -MultiViews 
    </IfModule> 

    RewriteEngine On 

    # Redirect Trailing Slashes If Not A Folder... 
    RewriteCond %{REQUEST_FILENAME} !-d 
    RewriteRule ^(.*)/$ /lumen/public/$1 [L,R=301] 

    # Handle Front Controller... 
    RewriteCond %{REQUEST_FILENAME} !-d 
    RewriteCond %{REQUEST_FILENAME} !-f 
    RewriteRule^index.php [L] 
</IfModule>