Force non-www/http to www/https only for some specific pages

Viewed 117

I was wondering is it's possible to force some specific pages from non-www/http to www/https and keep some other ones with non-www/http.

Example

From non-www/http to www/https:

http://example.com to https://www.example.com

but these ones will remain non-www and http:

http://example.com/folder1/*

http://example.com/folder2/*

I have tried to add in the htaccess file this rule condition:

RewriteEngine On     

# Enable HTTPS and WWW for homepage
RewriteCond %{REQUEST_METHOD} !POST
RewriteCond %{HTTPS} off
RewriteRule ^$ https://example.com/ [R=301,L]

# Disable HTTPS and WWW for all pages
RewriteCond %{REQUEST_METHOD} !POST
RewriteCond %{HTTPS} on
RewriteRule . http://%{HTTP_HOST}%{REQUEST_URI} [R=301,L,NE]

Then it should force to https and www just the homepage and leave the other pages like /folder1/ and /folder2/ to htpp non-www.

But it seems not working well

2 Answers

Try these :

RewriteEngine On
RewriteCond %{HTTPS} on
RewriteRule ^folder1.*$ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

RewriteEngine On
RewriteCond %{HTTPS} on
RewriteRule ^folder2.*$ http://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

RewriteEngine On
RewriteCond %{HTTPS} on
RewriteRule ^folder1.*$ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

RewriteEngine On
RewriteCond %{HTTPS} on
RewriteCond %{HTTP_HOST} ^www\.example\.com$
RewriteRule ^folder2.*$ http://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

RewriteEngine On
RewriteCond %{HTTPS} on
RewriteCond %{HTTP_HOST} ^www\.example\.com$
RewriteRule ^folder1.*$ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

and so on...

Try this:

RewriteEngine  On
RewriteCond    %{HTTPS} off       ## http requests only
RewriteRule    ^folder1/  - [L]   ## stop for folder1/ 
RewriteRule    ^folder2/  - [L]   ## stop for folder2/
                                  ## then redirect all other requests:
RewriteRule    ^(.*)$     https://www.example.com%{REQUEST_URI} [END,NE,R=permanent] 

Similarly, you can you regex your skips:

RewriteRule    ^folder(\d+)/  - [L]   ## stop redirection for any folder[number]/

Or make this a negative RewriteCond keeping a single RewriteRule:

RewriteEngine  On
RewriteCond    %{HTTPS} off                        ## http requests only
RewriteCond    %{REQUEST_URI}   !^/folder(\d+)/    ## skip any folder[number]/
RewriteRule    ^(.*)$     https://www.example.com%{REQUEST_URI} [END,NE,R=permanent] 

Etc... Full docs: https://httpd.apache.org/docs/2.4/rewrite/flags.html

Related