Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

htaccess: forcing https and www if not on localhost

I work on my localhost so I need this exception in my mod_rewrite rule. Currently, I am able to force the "www" when not on localhost using the following:

# Force www, if not in localhost
RewriteCond %{HTTP_HOST} !=localhost
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]

Now, I want to also force https (my entire site will be under https). How do I add this to my htaccess?

I tried making my htaccess like this, but this is forcing https on my localhost also:

# Force https, if not in localhost
RewriteCond %{HTTP_HOST} !=localhost    
RewriteCond %{HTTPS} !=on
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

# Force www, if not in localhost
RewriteCond %{HTTP_HOST} !=localhost
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]

UPDATE 1: I think I need to remove the first [R=301,L].

UPDATE 2: If I have a URL like this: https://scripts.domain.com, I do not want it to become: https://www.scripts.domain.com.

like image 485
StackOverflowNewbie Avatar asked Sep 23 '12 09:09

StackOverflowNewbie


People also ask

How do I fix htaccess mixed content issue?

You can fix NGINX mixed content issues by inserting a couple of lines of code into the . htaccess file in the root directory. All you need to do is open the . htaccess file, paste some code, change the default URL to your own URL and save the file.


1 Answers

Add this line above your last rule:

RewriteCond %{HTTP_HOST} ^[^.]+\.[^.]{3}$
like image 180
Jon Lin Avatar answered Oct 02 '22 22:10

Jon Lin