1

My url contains a broken link due to the http:// prefix not being added in places. How would I replace this using mod_rewrite:

http://website.com/www.websitelink.com 

should go here:

http://www.websitelink.com 
3
  • search for htaccess on stackoverflow. Someone will have already answered this. Commented Nov 26, 2010 at 11:38
  • Wouldn't it be better to fix the offending links? Or are they beyond your control? Commented Nov 26, 2010 at 11:59
  • the links are beyond my control unfortunately... Commented Nov 26, 2010 at 12:01

1 Answer 1

3
RewriteRule ^www\.websitelink\.com$ http://www.websitelink.com/ [R=301,NC,L] 

In other words, if your path is /www.websitelink.com (^ is start of string,$ is end of string; in regular expressions, dots are one-character wildcards and have to be escaped)
(and [NC] matching is not case sensitive - /WwW.webSiteLink.COM would match, too),

[R=301] redirect with status "301 (Moved Permanently)"
to http://www.websitelink.com/
and [L] leave processing (no more rewrite rules are processed).

Note that this will work regardless of the site's domain (would work e.g. for http://website.com/www.websitelink.com and http://www.website.com/www.websitelink.com )

If you want to match all the paths that end with your domain, drop the starting ^:

RewriteRule www\.websitelink\.com$ http://www.websitelink.com/ [R=301,NC,L] 

and if you want to match even paths without www., make it optional:

RewriteRule (www\.)?websitelink\.com$ http://www.websitelink.com/ [R=301,NC,L] 

As @Litso noted, this won't match the path after the "domain-in-path"; this should match the trailing path:

RewriteRule (www\.)?websitelink\.com/(.*)$ http://www.websitelink.com/$1 [R=301,NC,L] 

To match any subdomain:

RewriteRule ([a-z0-9.-]+\.)?websitelink\.com/(.*)$ http://www.websitelink.com/$1 [R=301,NC,L] 

And to match any domain:

RewriteRule ([a-z0-9.-]+\.)?([a-z0-9.-]+)\.com/(.*)$ http://www.$1.com/$2 [R=301,NC,L] 
Sign up to request clarification or add additional context in comments.

7 Comments

If you want to replace all traffic that includes the domain name as a folder and not just the main page, use: RewriteRule ^www\.websitelink\.com/(.*)$ http://www.websitelink.com/$1 [R=301,NC,L] The (.*) catches evertything behind the domainname.com and $1 inserts that back into the right url
this doesnt seem to be working for me: some of the URLS dont have the www. prefix i.e.: mywebsite.com/myfolder/websitelink.co.uk
@Litso: Quite correct. Do you want to post that as your own answer, or shall I edit it into mine?
@InnateDev: If they don't have the prefix, of course they won't match the pattern which contains the prefix. That's a little bit different from your question; edited my answer.
@piskvor just add it to yours ;)
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.