简体   繁体   中英

How to apply an htaccess rule only on https

So I have a protected folder on a site with an htaccess that forces https and uses basic authentication. The problem is that if I go there using http, it asks for authentication before transferring to https, and then asks for authentication again. Is there a way to make it transfer to https before it prompts me?

Here is the htaccess:

RewriteEngine On
RewriteCond %{SERVER_PORT} 80
RewriteCond %{REQUEST_URI} folder
RewriteRule ^(.*)$ https://site.net/folder/$1 [R,L]
AuthName "Dialog prompt"
AuthType Basic
AuthUserFile /home/user/site.net/folder/.htpasswd
Require valid-user

Update: I've decided to implement my own auth system to bypass this issue.

This is what you can do to show authentication only once:

  1. Set a cookie while redirecting from http to https
  2. Using SetEnvIfNoCase disable authentication when cookie is set

Code you can use:

RewriteEngine On

RewriteCond %{HTTPS} off
RewriteRule ^filder https://%{HTTP_HOST}/folder%{REQUEST_URI} [R,L,NC,CO=NO_AUTH:1:%{HTTP_HOST}]

SetEnvIfNoCase COOKIE NO_AUTH=1 OKAY

AuthType Basic
AuthName "Dialog prompt"
AuthUserFile /home/user/site.net/folder/.htpasswd
Require valid-user
Order allow,deny
allow from all
deny from env=OKAY
Satisfy any

If you are on Apache 2.4, you can apparently use the conditional structure within your htaccess:

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}

<If "%{HTTPS} == 'on'">
    AuthType basic
    AuthName "Private"
    AuthUserFile /path/to/passwordfile
    Require valid-user
</If>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM