-1

I am trying to enforce https://www. on all of my pages except hotels.php. My current code below is adding www. twice, i.e. https://www.www.example.com

.htaccess

RewriteEngine On
RewriteCond %{HTTPS} =off
RewriteCond %{REQUEST_URI} !^\/hotels.php\/
RewriteRule (.*) https://www.%{HTTP_HOST}/$1 [L,R=301]    

RewriteCond %{HTTPS} =on
RewriteCond %{REQUEST_URI} \/hotels.php\/
RewriteRule (.*) http://www.%{HTTP_HOST}/$1 [L,R=301]

Let me know what I am missing here which causing issue. Thanks

Quasimodo's clone
  • 5,511
  • 2
  • 18
  • 36
Raju Bhatt
  • 365
  • 4
  • 14
  • Already been asked and answered in Stackoverflow. – jasie Jan 15 '19 at 14:12
  • @jasie Please vote to close / flag as duplicate with the apropriate Q/A. – Quasimodo's clone Jan 15 '19 at 14:13
  • Rewriting configured in .htaccess “loops” until no rules match any more. _After_ you have externally redirected to `https://www.example.com/foo` already (or if you requested this to begin with), your first set of conditions & rules redirects again - but the `HTTP_HOST` variable now contains `www.example.com` already, to which you add another `www.` in front. You need an additional condition in that place that checks if the host name does not start with `www.` already, see https://stackoverflow.com/a/4958847/10283047 for an example. – misorude Jan 15 '19 at 14:13
  • Possible duplicate of [Htaccess redirection exception](https://stackoverflow.com/questions/52037601/htaccess-redirection-exception) – jasie Jan 15 '19 at 14:18

3 Answers3

2

Try these rewrite conditions:

RewriteEngine On

RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^ https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

# force https:// for all except your desired URLs    
RewriteCond %{HTTPS} off
RewriteCond %{THE_REQUEST} !/hotels.php/ [NC]
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

# force http:// for your desired URLs
RewriteCond %{HTTPS} on
RewriteCond %{THE_REQUEST} /hotels.php/ [NC]
RewriteRule ^ http://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
0

Not a master with Htaccess regex, bit this works for me:

<IfModule mod_rewrite.c>
    RewriteCond %{HTTPS} off [OR]
    RewriteCond %{HTTP_HOST} !^www\. [NC]
    RewriteCond %{HTTP_HOST} ^(.*)$  [NC]
    RewriteRule (.*) https://www.%1/$1 [R=301,L]
</IfModule>

Hope it helps! There's lot of answers to this on StackOverflow... pretty sure that probably where I got the above!

Dammeul
  • 1,209
  • 11
  • 20
0

You have to check if www is in the request URI as you check HTTPS. Try this:

//If has not www and it's not a subdomain adds www
RewriteCond %{HTTP_HOST} !^www\.
RewriteCond %{HTTP_HOST} !^(.*)\.(.*)\. [NC]
RewriteRule .* http://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

//If has not https and it's not hotels.php add https
RewriteCond %{REQUEST_SCHEME} !https
RewriteCond %{REQUEST_URI} !^\/hotels.php\/
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
kikerrobles
  • 1,647
  • 2
  • 14
  • 25