AlexioVay
AlexioVay

Reputation: 4527

htaccess: How to redirect to non-www domain in subfolder?

I'm using this code in my htaccess file:

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

RewriteCond %{HTTPS} on
RewriteCond %{HTTPS_HOST} ^www\.(.*)$
RewriteRule ^(.*)$ https://%1/$1 [R=301,L]

This redirects to the non-www version of a domain, but if I'm in a subfolder like https://www.example.com/test/ nothing happens. How can my code affect subfolders too?

Upvotes: 0

Views: 216

Answers (1)

freedev
freedev

Reputation: 30137

HTTPS_HOST does not exist, read the Apache HTTPD documentation.

The following variables provide the values of the named HTTP request headers.

Name

  • HTTP_ACCEPT
  • HTTP_COOKIE
  • HTTP_FORWARDED
  • HTTP_HOST
  • HTTP_PROXY_CONNECTION
  • HTTP_REFERER
  • HTTP_USER_AGENT

Given that HTTPS_HOST doesn't exist when RewriteCond %{HTTPS} on is matched you're rewrite wasn't working at all.

You should use in both cases HTTP_HOST, and given that your rewrites are identical for both HTTP and HTTPS why don't simply have:

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

In case the suggested solution does not work I suggest to enable rewrite log:

LogLevel alert rewrite:trace3

Pay attention to not deploy such logging in production because it affects server performances.

Upvotes: 1

Related Questions