Rewrite rules for https only for login with htaccess

.htaccessapache-2.2httpsrewrite

I am using apache, and i have on my index page (index.php) a login and password field.
The authentification is made with the login.php page and then if i am authaurize i can reach the next page home.php.

I want to secure the authentification with https, but only for the authentification, so i need to set up a url rewriting.

RewriteCond %{HTTPS} !on 
RewriteCond %{REQUEST_URI} ^/login.php 
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,QSA,L]

I have think about this solution but it doesn't work. I can enter my credentials on the index.php and then I am redirect to the login.php with https, but i still have to complete the login and password field.

Have you any idea ?

Best Answer

Do not do this!

Your credentials are being sent in a POST request, unencrypted. The server gets that request, and responds with the configured redirect instead of passing the request to PHP. Your client sees that redirect, and does not resubmit the POST request against it; after all, it sent the POST request to where it was supposed to send it and got a non-error response code (301). It sends a GET request over the new HTTPS channel, which doesn't contain the credentials; they need to be re-entered as you're seeing.

Instead of what you're doing, implement it like this:

  1. Your HTML form that's being submitted must be pointed to the https:// address for the credentials to be submitted securely. No exceptions.
  2. To make sure that you don't accidentally have exceptions in your code, prevent all access to the login form over HTTP, instead of redirecting.

    RewriteCond %{HTTPS} !on 
    RewriteCond %{REQUEST_URI} ^/login\.php [NC]
    RewriteRule ^ - [F,L]
    
Related Topic