1
\$\begingroup\$

I'm trying to write some mod rewrite code to redirect pages on a site to always use www and this has been working fine:

RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]

However, I now want to make sure this doesn't happen on my dev environment, which uses the .local domain extension...

So I changed it to this:

RewriteCond %{HTTP_HOST} !\.local$
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]

Does that seem correct?

As I understand it, it states: "If it doesn't END with .local AND it doesn't START with www. THEN do the RewriteRule"?

\$\endgroup\$
2
  • \$\begingroup\$ Does that seem correct? Does it work? Did you test it? \$\endgroup\$ – yuri Jul 24 '18 at 16:46
  • \$\begingroup\$ @yuri It seems to work locally, but I am unable to test it elsewhere yet; and even if it did work, that doesn't mean it's 100% correct code, hence my question. :) \$\endgroup\$ – Brett Jul 24 '18 at 17:12
1
\$\begingroup\$

Yes! That is indeed correct. From the docs for RewriteCond:

'ornext|OR' (or next condition)

Use this to combine rule conditions with a local OR instead of the implicit AND.

The [AND] flag is the default behaviour of combining multiple conditions expressions together.

As for the rule itself, I'd suggest using %{REQUEST_URI} instead of $1 in rewrites:

RewriteCond %{HTTP_HOST} !\.local$
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^ http://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
\$\endgroup\$
3
  • \$\begingroup\$ Thanks. Is there a reason you suggest using %{REQUEST_URI} over $1 and why is the ^ portion of that last rule needed - seems pointless now? \$\endgroup\$ – Brett Jul 26 '18 at 20:45
  • \$\begingroup\$ Not much if it is being used from .htaccess, but at VHost level or server level config, $1 will contain a leading /, causing rewrite to <host>//<path> (double / in URL) \$\endgroup\$ – hjpotter92 Jul 27 '18 at 7:40
  • \$\begingroup\$ Gotcha - cheers! :) \$\endgroup\$ – Brett Jul 27 '18 at 13:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.