简体   繁体   中英

Dynamic 301 .htaccess Redirect/Rewrite

I have a website with a forum and here is the current rewrite rule in my htaccess file:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^.*/?forum/?(.*)$ /forum.php [L]

Now, because of that I have urls indexed by Google like:

www.domain.com/abc/forum/rest-of-url  
www.domain.com/defg/forum/rest-of-url   
www.domain.com/something-else/forum/rest-of-url 

and all links are showing the same page, which should be access only as:

www.domain.com/forum/rest-of-url 

without any words(abc, defg, etc) between the domain/ and /forum/

Basically anything like this link:

www.domain.com/abc/forum/rest-of-url

should be 301 redirect to:

www.domain.com/forum/rest-of-url 

I tried changing the rewrite rule to:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule /forum/?(.*)$ /forum.php [L]

But then I get lots of 404 errors in Google Webmaster tools for all previously indexed URLs, so I think there is a work around with 301 redirect, but I haven't figured out how to avoid going in a loop.

Any help is appreciated. Thanks

Enable mod_rewrite and .htaccess through httpd.conf and then put this code in your .htaccess under DOCUMENT_ROOT directory:

Options +FollowSymLinks -MultiViews
# Turn mod_rewrite on
RewriteEngine On
RewriteBase /

# redirect any /foo/forum/index to /forum/index
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^[^/]+/(forum/[^/]+/?)$ /$1 [L,R=301,NC]

Once you verify it is working fine, replace R=302 to R=301 . Avoid using R=301 (Permanent Redirect) while testing your mod_rewrite rules.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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