Saturday, March 19, 2022

[FIXED] Htaccess conditional https for static pages

Issue

My site is HTTPS enabled and all the pages are served using HTTPS only. Client now has the requirement where he wants to show static pages like about-us, termsofus as HTTP pages and not as HTTPS. This means that even if the user tries to open about-us page as HTTPS it should redirect to HTTP version of about-us.

My .htaccess code is as follows:

Options -Indexes

<IfModule mod_rewrite.c>

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

RewriteCond %{HTTPS} off
RewriteCond %{REQUEST_URI} !^\/about-us
RewriteCond %{REQUEST_URI} !^\/termsofus
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

RewriteCond %{HTTPS} on
RewriteCond %{REQUEST_URI} \/about-us [OR]
RewriteCond %{REQUEST_URI} \/termsofus
RewriteRule (.*) http://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . index.php
</IfModule>

Problem: Whenever I open HTTP/HTTPS version of about-us page it keeps on redirecting me to index.php. For example: https://example.com/about-us to https://example.com/index.php

The site uses PHP YII framework.


Solution

Use THE_REQUEST variable instead of REQUEST_URI. THE_REQUEST variable represents original request received by Apache from your browser and it doesn't get overwritten after execution of some rewrite rules.

Options -Indexes

RewriteEngine on

RewriteCond %{HTTPS} off
RewriteCond %{THE_REQUEST} !\s/+(about-us|termsofus) [NC]
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301,NE]

RewriteCond %{HTTPS} on
RewriteCond %{THE_REQUEST} \s/+(about-us|termsofus) [NC]
RewriteRule ^ http://%{HTTP_HOST}%{REQUEST_URI} [L,R=301,NE]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . index.php

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



Answered By - anubhava

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.