user2807681
user2807681

Reputation: 99

htaccess - How to make the "www" in an URL optional?

I try to write a redirect that works if a page is accessed with only http:// and also with http://www..

This is what I've got:

RewriteCond %{REQUEST_URI} ^(.*)$example.com$

This should work no matter how the URL begins, but I would like to be as specific as possible.

I already tried something like this, but it didn't work:

RewriteCond %{REQUEST_URI}  ^(http:\/\/)$^(www\.)$example.com$

How do I have to write a rewrite condition that works for a pages with only http:// and http://www.?

Upvotes: 0

Views: 614

Answers (1)

zx81
zx81

Reputation: 41848

Use this:

RewriteCond %{REQUEST_URI} ^/?(?:www\.)?example\.com$ [NC]

Notes

  • (?:www\.)? gives you an optional www. group
  • [NC] makes the match case-insensitive

Upvotes: 1

Related Questions