user332951 user332951 - 1 month ago 7
Apache Configuration Question

.htaccess https to http redirect conflict with existing rule

Currently we have this rule in .htaccess

RewriteEngine on <br>
RewriteCond %{REQUEST_URI} !^/site/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /site/$1
RewriteRule ^(/)?$ site/index [L]


What this does is for any visit we will redirect to subfolder call site if the page not found. And when this happen the url will not show site as subfolder.

Example if we have
/rootFolder/site/temp.html this will show in url as

http://www.domain.com/temp.html

This is working fine but now we need to add https redirect if user visit site.

This is the new rule I came up with

RewriteEngine on
RewriteCond %{HTTPS} off
RewriteCond %{REQUEST_URI} !^/site/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ https://%{HTTP_HOST}/site/$1
RewriteRule ^(/)?$ https://%{HTTP_HOST}/site/index [L]


But the issue with this one is now url will show site subfolder
https://www.domain.com/site/temp.html

How can I achieve so that if user does

http://www.domain.com/temp.html it will find temp.html in site subfolder and redirect to https and url will only show

https://www.domain.com/temp.html

Thanks

Answer

How about if you do it in two passes, always redirecting whatever was requested to https, then running your rewrite rules, like so:

RewriteCond %{HTTPS} off
#301 flag redirects instead of rewriting
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

#leaving your original rules as is
RewriteCond %{REQUEST_URI} !^/site/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /site/$1
RewriteRule ^(/)?$ site/index [L]