Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirecting all traffic to www https

My application is running on Apache hosted on Ubuntu and I want the following re - directions to work:

1> http://example.com       -> https://www.example.com
2> http://www.example.com   -> https://www.example.com
3> https://example.com      -> https://www.example.com

I am using the following lines in my default apache config file :

RewriteEngine on
RewriteCond %{HTTP_HOST}   !^$
RewriteRule ^/?(.*)         https://www.example.com/$1 [L,R]

This way , the first two redirections work fine but the third one does not. Is the third one possible? if yes how?

Thanks.

like image 682
SNAG Avatar asked Jun 22 '26 22:06

SNAG


1 Answers

I have a site that I want all traffic coming into a virtual host to go to port 443. I set up the virtual host definition for port 80 redirection as follows:

RewriteEngine on
RewriteCond %{SERVER_PORT} !^443$
RewriteRule ^/?(.*)         https://www.example.com/$1 [L,R]

This will redirect any traffic coming into port 80 to 443.

Make sure that you have your ServerName and ServerAlias set up correctly. In this example you would have something like:

<VirtualHost *:80>
    ServerName www.example.com
    ServerAlias *.example.* example.* example.com

    <IfModule mod_rewrite.c>
        RewriteEngine On
        RewriteCond %{REQUEST_METHOD} ^TRACE
        RewriteRule .* - [F]
        RewriteCond %{REQUEST_METHOD} ^TRACK
        RewriteRule .* - [F]

        #redirect all port 80 traffic to 443
        RewriteCond %{SERVER_PORT} !^443$
        RewriteRule ^/?(.*) https://www.example.com/$1 [L,R]
    </IfModule>

</VirtualHost>

After this you would set up a 443 virtualhost definition as well (less the port rewrite section).

like image 174
Russell Shingleton Avatar answered Jun 25 '26 15:06

Russell Shingleton