.htaccess SSL redirect with url rewrite

2019-09-16 09:52发布

问题:

I need your help. Let's say this is my website: example.com

I would like to redirect http to https. Furthermore I would like also rewrite the url. If i access the website with:

https://example.com/new everything is working fine.

If I access the website with: http://www.example.com/new it redirects to https but will not rewrite the url. The result is this:

`https://example.com/old`


RewriteEngine on

RewriteRule  ^new/(.*)$    old/$1    [L,QSA] 

RewriteCond %{HTTPS} =off [NC,OR]
RewriteCond %{HTTP_HOST} ^example.com [NC,OR]
RewriteCond %{HTTP_HOST} ^www.example.com [NC,OR]
RewriteCond %{HTTP_HOST} ^www.example.com [NC]
RewriteRule ^(.*)$ https://example.com/$1 [L,R=301,NC]

I have tried to put the rules in another order but this wasn't working at all.

I hope you can help me. Many thanks:)

回答1:

If you are only trying to remove www, you just need this.

RewriteEngine on

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

RewriteRule  ^new/(.*)$    old/$1    [L,QSA]


回答2:

The rule

RewriteRule  ^new/(.*)$    old/$1    [L,QSA] 

is configured as L (last), hence it no longer processes other rules once it matches.

You need to switch the order of the rules. Add the HTTPS redirect before the mentioned rule.