Redirect http to https return double slashes

5,247

That's because you are grabbing the first slash in (.*):

RewriteRule ^(.*)$ https://%1/$1 [R=301,L]

This kind of regex is used in per-dir context, where the first slash is not used and does not apply, in virtualhost context first slash is present so you are capturing and adding it to the result with (.*).

So one the most typical and correct way to do it in virtualhost context is adding the slash manually before the capture group:

RewriteRule ^/(.*) https://%1/$1 [R=301,L]

Note: I removed the "$" because when you capture everything it is not necessary to specify "the end".

Share:
5,247

Related videos on Youtube

Hady Shaltout
Author by

Hady Shaltout

Updated on September 18, 2022

Comments

  • Hady Shaltout
    Hady Shaltout over 1 year

    My System is Centos 7 and Apache 2.4.6

    I need to redirect http to https using Apache httpd.conf, I googled hundreds pages and I found some codes but this is good and not hard coded from DigitalOcean but it return double slash at the end of URL and this is an image for the different redirect results

    <VirtualHost IP:80>
    
       # https/http www -> https non-www
    
       RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
       RewriteRule ^(.*)$ https://%1/$1 [R=301,L]
    
       # http non-www -> https non-www
       RewriteCond %{HTTPS} !=on
       RewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [R,L]
    
    </VirtualHost>
    
    <VirtualHost IP:443>
    
       # I removed this from 443 and the same result
       # https/http www -> https non-www
       RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
       RewriteRule ^(.*)$ https://%1/$1 [R=301,L]
    
    </VirtualHost>
    
  • Hady Shaltout
    Hady Shaltout about 6 years
    Thank you pal, Can you give me the RegEx to convert non www to https :// www ??
  • ezra-s
    ezra-s about 6 years
    what I do is generate the appropiate virtualhost and redirect from one to the other with a simple Redirect / https://www.example.com/. Remember, simpler options first, and regex by nature is anything but simple :)
  • Hady Shaltout
    Hady Shaltout about 6 years
    Ezra-s it doesn't work in the first so I start searching about another solution .. Thanks