0
votes

I have few pages which need to be secured through mod_rewrite and the code is based on mvc architecture

Let me say I have a page login its url is http://www.example.com/login it needs to be redirected to https://www.example.com/login

If any url other than desired secured url uses https we need to change it to http for example https://www.example.com/sitemap must be redirected to http://www.example.com/sitemap

I am using the following code in .htaccess

  RewriteCond %{SERVER_PORT} !^443$
  RewriteRule ^login$ https://%{HTTP_HOST}/login [R=301,L]

  RewriteCond %{SERVER_PORT} ^443$
  RewriteCond %{REQUEST_URI} !^/login$
  RewriteRule ^(.*)$ http://%{HTTP_HOST}/$1 [R=301,L]

  # we check if the .html version is here (caching)
  RewriteRule ^$ index.html [QSA]
  RewriteRule ^([^.]+)$ $1.html [QSA]
  RewriteCond %{REQUEST_FILENAME} !-f

  # no, so we redirect to our front web controller
  RewriteRule ^(.*)$ index.php [QSA,L]

The problem I get is, it gets looped where it says "server is redirecting the request for this address in a way that will never complete".

Can you please help me out with the solution where only the following urls are secured and others are not. I need a solution with .htaccess and not with any symfony plugin.

https://www.example.com/login

https://www.example.com/account

https://www.example.com/register

Thanks

Nizam

2

2 Answers

0
votes

I think the problem is an unwanted slash in your fifth line's regex. Try this

RewriteCond %{SERVER_PORT} !^443$
RewriteRule ^login$ https://%{HTTP_HOST}/login [R=301,L]

RewriteCond %{SERVER_PORT} ^443$
RewriteCond %{REQUEST_URI} !^login$
RewriteRule ^(.*)$ http://%{HTTP_HOST}/$1 [R=301,L]
0
votes

This worked perfectly for me

  # SSL here
  RewriteCond %{SERVER_PORT} !^443$
  RewriteRule ^/?(login|account|register|mypage)(.*) https://%{HTTP_HOST}/$1$2 [R,L]

  # not anywhere else
  RewriteCond %{SERVER_PORT} !^80$
  RewriteCond %{REQUEST_URI} !^/?(login|account|register|mypage)(.*)
  RewriteCond %{REQUEST_URI} !^/?index\.php$
  RewriteRule .? http://%{HTTP_HOST}%{REQUEST_URI} [R,L]

Thanks Prem, Amar, Harry for the solution.