0

I recently migrated my website from HTTP to HTTPS. I read on various websites about redirecting all HTTP requests to HTTPS using .htaccess codes.

Lots of websites provide different codes and now I'm confused which code should I use.

Following are 4 codes found on various websites:

1st code:

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

2nd code:

RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [R,L]

3rd code:

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

4th code:

NameVirtualHost *:80
<VirtualHost *:80>
ServerName www.example.com
Redirect permanent / https://secure.example.com/
</VirtualHost>

<VirtualHost _default_:443>
ServerName secure.example.com
DocumentRoot /usr/local/apache2/htdocs
SSLEngine On
</VirtualHost>

Please guide me which code is perfect and I should put in my .htaccess file?

TSA
  • 157
  • 2
  • 11
  • 2
    It depends on your own environment, since each of these examples have their own assumptions on the environment they are running in. – Tero Kilkanen Sep 24 '17 at 19:28
  • 1
    Option #1 is invalid (possibly taken out of context?). From your other questions, it seems you have access to the server config, so this isn't something you should be doing in `.htaccess` anyway, as HBruijn suggests below. – MrWhite Sep 24 '17 at 22:29

1 Answers1

2

For starters: the last configuration snippet is not even valid in .htaccess files...

(But since you shouldn't be using .htaccess files anyway if you're a system administrator that's not an issue.)

Redirecting http to https a text book example of when (as an admin) you should not need a mod_rewrite approach and use a simple redirect instead. So, if you do have access to the main server config, your last snippet with a simple redirect from the plain http VirtualHost is recommended.

HBruijn
  • 72,524
  • 21
  • 127
  • 192
  • I have access to the main server config and I'm using 3rd code in `pre_virtualhost_global.conf` file. When I checked the apache.org link shared by you, it doesn't contain `NameVirtualHost *:80` line at the beginning and there are some more changes between 4th code shared by me and the code given at apache.org. Can you please tell me which code is correct? – TSA Sep 25 '17 at 06:16
  • 1
    Please don't blindly follow recipes without understanding what to do: http://blog.lastinfirstout.net/2009/11/cargo-cult-system-administration.html - as Tero already commented, it depends a bit on what else is configured. – HBruijn Sep 25 '17 at 06:57
  • We cannot tell which one to use since we don't know about your configuration. – Tero Kilkanen Sep 25 '17 at 19:37