Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making www optional in htaccess rule

Tags:

.htaccess

I have following .htaccess to point a domain to a subfolder.

RewriteEngine on
RewriteBase /
RewriteCond %{HTTP_HOST} site.com
RewriteCond %{REQUEST_URI} !folder_site/
RewriteRule ^(.*)$ folder_site/$1 [L]

How can I change RewriteCond %{HTTP_HOST} site.com to also include www as an optional match.

like image 536
8thperson Avatar asked Dec 24 '22 09:12

8thperson


2 Answers

RewriteCond %{HTTP_HOST} ^(?:www\.)?site\.com$
like image 135
Brandon Harris Avatar answered Dec 28 '22 09:12

Brandon Harris


The first line sets a condition: only if the condition is true, the second line will be processed. The condition could be 'translated' to: "if the host name doesn't start with www.". The regular expression !^www. means this:

! = not

^ = start

. = . (the backslash is the escape character, because dots have a special meaning in regular expressions, and therefore must be escaped) So !^www\. means "doesn't start with www."

The last line is the actual rewrite rule: again it uses regular expressions to match certain urls, and then rewrites them to something else. The first part is the regular expression:

^(.*)$

This means: anything! You already know the ^ sign. The (.*) bit means zero or more characters (the dot means any character, the asterisk means zero or more). The final $ means 'end'.

Then comes the bit that says how to rewrite the url,

for example:

http://www.%{HTTP_HOST}/$1 [R=301,L]

%{HTTP_HOST} will be replaced by the host name (i.e. anything.com).

$1 references whatever was matched in the regular expression between the brackets, which in this case is everything.

The [R=301,L] means "inform the user agent that this is a permanent redirect (HTTP 301 code), and don't process any more rewrite rules (if there were any after this one).

If you're not familiar with regular expressions, this might still look a bit abstract, feel free to ask for more details. :)

like image 33
Ankush Rishi Avatar answered Dec 28 '22 09:12

Ankush Rishi