Brad Brad - 13 days ago 4
HTTP Question

htaccess file: Force going to https instead of http except for specific pages

I have read a lot about this, but i still can't figure it out for my case. I am trying to force all http requests to go to https except for 2 pages. Those 2 pages requests have parameters passed to them. Here is the code i am using currently:

# Force go to https if user isn't asking for a url that has 'register_user.php' or 'register-customer' inside the url:
RewriteCond %{SERVER_PORT} 80
RewriteCond %{REQUEST_URI} !^/register_user.php$ [OR]
RewriteCond %{REQUEST_URI} !^/register-customer$ [NC]
RewriteRule ^(.*)$ https://www.myWebsite.com/main-folder/$1 [R,L]

# Force go to http if user is asking for a url that has 'register_user.php' or 'register-customer' inside the url:
RewriteCond %{SERVER_PORT} !80
RewriteCond %{REQUEST_URI} ^/register_user.php$ [OR]
RewriteCond %{REQUEST_URI} !^/register-customer$ [NC]
RewriteRule ^(.*)$ http://www.myWebsite.com/main-folder/$1 [R,L]


This code doesn't do the required job. Is there something wrong with it?

Answer

You should use THE_REQUEST instead of REQUEST_URI as REQUEST_URI may change due to other rules.

Also you should keep these 2 rules at the top before other rules:

# Force go to https if user isn't asking for a url that has 'register_user.php' or 'register-customer' inside the url:
RewriteCond %{HTTPS} off
RewriteCond %{THE_REQUEST} !/(register-customer|register_user\.php)[?/\s]  [NC]
RewriteRule ^ https://%{HTTP_HOST}/main-folder%{REQUEST_URI} [R=301,NE,L]

# Force go to http if user is asking for a url that has 'register_user.php' or 'register-customer' inside the url:
RewriteCond %{HTTPS} on
RewriteCond %{THE_REQUEST} /(register-customer|register_user\.php)[?/\s]  [NC]
RewriteRule ^ http://%{HTTP_HOST}/main-folder%{REQUEST_URI} [R=301,NE,L]

Make sure to clear your browser cache before testing this change.