V
V
Viktor Taran2017-07-14 14:41:34
htaccess
Viktor Taran, 2017-07-14 14:41:34

How to save protocol during redirect?

The task is seemingly simple, to save the protocol when redirecting. But there is no standard method.
Given:

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

The problem is that there is no server response htttp or https can be off on true false but this is not to be sewn to the point.
There is Vary: HTTPS
but it does not return http at all.
Alternatively, something like
RewriteCond %{HTTP:X-Forwarded-Proto} http(s) [NC]
#RewriteCond %{HTTP_HOST} ^www\.(.*) [NC]
RewriteRule ^331/$ /best/http%1/%2/3 [L,R=301]

%1 works with the comment, but not with the second cond ;(

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Viktor Taran, 2017-07-14
@shambler81

RewriteCond %{ENV:HTTPS} on
RewriteRule .* - [E=SSL:s]
RewriteCond %{HTTP_HOST} !^www\.(.*) [NC]
RewriteRule ^(.*)$ http%{ENV:SSL}://www.%{HTTP_HOST}/$1 [R=301,L]

Thanks everyone, I found the solution myself.
If someone suggests something better, we'll look.

D
dodo512, 2018-05-22
@dodo512

Alternatively, something like
RewriteCond %{HTTP:X-Forwarded-Proto} http(s) [NC]
#RewriteCond %{HTTP_HOST} ^www\.(.*) [NC]
RewriteRule ^331/$ /best/http%1/%2/3 [L,R=301]

%1 works with the comment, but not with the second cond ;(

The result in %1-%9 is overwritten by the last successful pattern match.
Those. condition with a prefix !will not overwrite the results of the previous one.
RewriteCond %{HTTP:X-Forwarded-Proto} http(s)| [NC]
RewriteCond %{HTTP_HOST} !^www\.(.*) [NC]
RewriteRule ^(.*)$  http%1://www.%{HTTP_HOST}/$1 [R=301,L]

Another way is to cram both conditions into one RewriteCond.
Then the variants of the string to be checked can be as follows:
s on site.ru
s on www.site.ru
s off site.ru
s off www.site.ru

RewriteCond "s-%{HTTPS} %{HTTP_HOST}"  "^(?:(s)-on|\S+) (?!www\.)(.*)" [NC]
RewriteRule ^(.*)$ http%1://www.%2/$1  [R=301,L]

RewriteCond "s-%{HTTPS} %{HTTP_HOST}"  "^(?:(s)-on|\S+) www\.(.*)" [NC]
RewriteRule ^(.*)$     http%1://%2/$1  [R=301,L]

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question