.Htaccess rules to redirect respective HTTP links

2019-09-16 07:35发布

问题:

First, here's the .htaccess rule I currently use:

Options +FollowSymLinks
RewriteEngine on
RewriteRule (.*) http://example.com/$1 [R=301,L]

This is great, and redirects every link of my old domain to the very respective link in new domain. That is, http://olddomain.com/1.html is redirected to http://example.com/1.html and so forth.

But it doesn't redirect https://olddomain.com/1.html to https://example.com/1.html

And just so you know I tried, below are the rules I also happened to test. Unfortunately they're creating some kind of loop, and the redirection doesn't work.

Options +FollowSymLinks
RewriteEngine on
RewriteRule (.*) example.com/$1 [R=301,L]

and

Options +FollowSymLinks
RewriteEngine on
RewriteCond %{SERVER_PORT} ^443$ [OR]
RewriteCond %{HTTPS} =on
RewriteRule (.*) example.com/$1 [R=301,L]

So, can someone give me the rules redirect http pages to http and https pages to https? Thanks.

回答1:

#if https on
RewriteCond %{HTTPS} on
RewriteRule ^(.*)$ https://example.com/$1 [R=301,L]
#else
RewriteRule ^(.*)$ http://example.com/$1 [R=301,L]


回答2:

Your HTTPS rewritecond is incorrect. Cond is a regex, not an quality test. It should be

RewriteCond %{HTTPS} !^on

The %{HTTPS} var will only ever contain on or off. Never =on, so the match fails and triggers the redirect, even if https really is on.


update

For an unconditional HTTP->HTTPS redirect you'd need to redirect to an https URL. Your version just detects if HTTPS is *OFF, then redirects to the same url, causing a loop. What you need is:

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