Stack Overflow

Log In
Sign Up

current community

Stack Overflow

help
chat

Meta Stack Overflow

your communities

Sign up or log in to customize your list.

more stack exchange communities

company blog

Tour

Start here for a quick overview of the site

Help Center

Detailed answers to any questions you might have

Meta

Discuss the workings and policies of this site

About Us

Learn more about Stack Overflow the company

Business

Learn more about hiring developers or posting ads with us

By using our site, you acknowledge that you have read and understand our Cookie Policy, Privacy Policy, and our Terms of Service.

Join Stack Overflow to learn, share knowledge, and build your career.

Email Sign Up
Sign Up

or sign in with

Google

Facebook

Home

Public

Stack Overflow

Tags

Users

Jobs

Teams
Q&A for work

Learn More

Apache .htaccess redirect to HTTPS before asking for user authentication

Ask Question

up vote
25
down vote

favorite

6

This is my .htaccess:

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

AuthUserFile /etc/hi
AuthName "hi"
AuthType Basic
require valid-user

It asks for user authentication using http, meaning that password will be sent in plain text. It will than redirect to the https version and ask the password again.

How can i fix it?

apache .htaccess

share|improve this question

edited Jul 18 '12 at 18:19

Qiau

3,55832437

asked Apr 22 '12 at 10:16

cedivad

1,06442035

2

You need to have HTTP and HTTPS sites declared in separate virtual host entries, so config for one will not interfere with another. When done, the rewrite rule should be in http one and auth in https one (This all assumes that you access site over HTTPS only).
– LazyOne
Apr 22 '12 at 15:31

add a comment |

8 Answers
8

active

oldest

votes

up vote
11
down vote

accepted

I get around it this way. Just allow Non-SSL since it will be redirected then require auth once on SSL...

SetEnvIf %{SERVER_PORT} ^80$ IS_NON_SSL

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

AuthUserFile /etc/hi
AuthName "hi"
AuthType Basic
require valid-user
Allow from env=IS_NON_SSL

share|improve this answer

answered Apr 11 '13 at 3:46

Ben

19233

2

Elegant solution to a not entirely obvious problem. I ended up using Allow from env=!HTTPS where HTTPS is set on SSL requests, but the same concept applies. Thanks.
– Chris Heald
May 25 '13 at 7:04

1

SERVER_PORT is not an option available in SetEnvIf directive as per the documentation at httpd.apache.org/docs/2.2/mod/mod_setenvif.html#setenvif
– Alagappan Ramu
Mar 20 '14 at 19:18

4

Plus at least in my case it stills asks for authentication twice.
– LWC
Mar 22 '16 at 20:55

4

This does not work. (Apache 2.2)
– Tamás Bolvári
May 15 '16 at 21:37

@ChrisHeald could you post your solution as an answer? Because this one here does not work for me.
– Adam
Apr 18 '17 at 13:41

add a comment |

up vote
12
down vote

If you're running Apache 2.4 you can use configuration sections to solve this quite easily.

Eg...

# Redirect to HTTPS
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R,L]

# Authenticate users only when using HTTPS
# Enable for <v2.4
# SSLRequireSSL
# ErrorDocument 403 /secure-folder/
# Enable for >v2.4
<If "%{HTTPS} == 'on'">
AuthType Basic
AuthName "Special things"
AuthUserFile /etc/blah.htpasswd
# Prevent this 'Require' directive from overriding any merged previously
<IfVersion >= 2.4>
AuthMerging And
</IfVersion>
Require valid-user
# Enable for >v2.4
</If>

share|improve this answer

edited Aug 7 '17 at 8:06

LWC

371322

answered Oct 2 '14 at 5:45

Molomby

1,8121619

5

Definitely don't do this. Because of directive merging order (<If> is merged last), authenticated users will have access to any file or directory previously blocked with either <Directory> or <File>! For example, on ordinary server setups the .htaccess file will be granted access for valid users.
– alecov
Nov 8 '14 at 17:56

3

@Alek, I've added an 'AuthMerging' directive that I believe addresses the issue you raised. So all visitors are still redirected to HTTPS but any HTTPS requests require the visitor to be authenticated in addition to existing restrictions added by previously merged <file> or <directory> directives. What do you think?
– Molomby
Dec 5 '14 at 2:16

2

I didn't test this setup, but it seems ok from the documentation, so I'll take your word out of it.
– alecov
Mar 7 '15 at 14:51

1

@Molomby, please remove the inline comment though: Comments may not be included on the same line as a configuration directive.
– LWC
Mar 22 '16 at 21:02

add a comment |

up vote
9
down vote

Thank you very much, Istador!

My Apache is of version 2.2 (Synology NAS DSM 5.1) so these two do not work on it:

RewriteOptions Inherit
IfVersion

After taking them (and the section of version >= 2.4) out. The whole thing began to work for me.

There are a lot suggestions out there for this topic, I spent two days to try them out.

But only this one works for me.

Here's what I did:

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

AuthType Basic
AuthName "private area"
AuthUserFile /path/to/file/.htdigest

Order Deny,Allow
Deny from all
Satisfy Any
Allow from env=!HTTPS
Require valid-user

So it's verified to work on Apache 2.2, Synology DSM 5.1.

share|improve this answer

edited May 10 '15 at 9:44

Bojan Kseneman

12.3k13948

answered May 10 '15 at 7:56

MXW

9111

Please don't add "thank you" as an answer. Once you have sufficient reputation, you will be able to vote up questions and answers that you found helpful.
– Ilya
May 10 '15 at 9:18

That is odd. According to the documentation of Apache 2.2 for mod_rewrite (for Apache 1.3 and later) and mod_version (for Apache 2.0.56 and later) both directives should be valid, assuming that both modules are installed.
– Istador
Jun 28 '15 at 15:56

2

@Ilya. The 'thank you' is helpful, as the post relates to their specific post, which is helpful in providing context for a reader like me. Without it, a reader might assume it is directly addressing only the OP's post. Of course, they could have just done an '@Istador' to be more concise!
– Patanjali
Oct 18 '16 at 23:55

This doesn't seem to be working on the Debian-based version of 2.2 I have - the Allow from env=!HTTPS seems to have no effect, resulting in all pages bypassing the auth step.
– fooquency
Jul 15 at 17:03

add a comment |

up vote
3
down vote

The checked solution https://stackoverflow.com/a/15940387/2311074 does work on Firefox on Ubuntu 16.04, but it does not work on Firefox on Win 7.

If you want to protect your folder https://yourdomain.com/securefolder
then you need to create in that folder a .htaccess with the following content:

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

SSLRequireSSL
ErrorDocument 403 https://yourdomain.com/securefolder
AuthType Basic
AuthName "Admin"
AuthUserFile /outside/your/www/folder/.htpasswd
Require user admin Admin

The way it works is that when you are calling the website through http:// instead of https:// it will redirect you to the error page. The trick is to use the correct link with the https:// as your default error page.

share|improve this answer

edited May 23 '17 at 12:34

Community♦

11

answered Apr 19 '17 at 9:06

Adam

2,86832458

add a comment |

up vote
2
down vote

Our client's webapp is installed in his webuser directory. Authorisation is handled before mod_rewrite rules (https://serverfault.com/a/443185/253111), and we could not get the accepted answer to work, so mod_rewrite seemed not an option.

Eventually we explicitly required SSL and used the webapp's root over HTTPS as 403 and 404 error documents. So when one visits any page over HTTP (which is unauthorized, hence the 403) or a non existing page (404), he is being redirected to ie. https://DOMAIN.TLD/~WEBUSER/admin.

This is the .htaccess file with some extra info in the comments.

### INFO: Rewrites and redirects are handled after authorisation
### @link https://serverfault.com/a/443185/253111

### INFO: Log out of a HTPASSWD session
### This was not always possible, but Firefox and Chrome seem to end sessions
### when a new one is trying to be using ie.:
### https://logout:[email-masked]/~WEBUSER/
### @link http://stackoverflow.com/a/1163884/328272

### FORCE SSL: Explicitly require the SSL certificate of a certain domain to
### disallow unsigned certificates, etc. ErrorDocument commands are used to
### redirect the user to an HTTPS URL.
### @link http://forum.powweb.com/showthread.php?t=61566
SSLOptions +StrictRequire
SSLRequireSSL
SSLRequire %{HTTP_HOST} eq "DOMAIN.TLD"

### HTPASSWD AUTHENTICATION
AuthUserFile /var/www/vhosts/DOMAIN.TLD/web_users/WEBUSER/.htpasswd
AuthType Basic
AuthName "Hello"
Require valid-user

### ERROR DOCUMENTS: Redirect user in case of a 403 / 404.
ErrorDocument 403 https://DOMAIN.TLD/~WEBUSER/admin
ErrorDocument 404 https://DOMAIN.TLD/~WEBUSER/admin

share|improve this answer

edited Apr 13 '17 at 12:13

Community♦

11

answered Feb 17 '15 at 11:55

lmeurs

11.5k22129

Why do you need SSLRequire %{HTTP_HOST} eq "DOMAIN.TLD"? For which case does this help? By the way: SSLRequire is depreciated httpd.apache.org/docs/current/mod/mod_ssl.html#sslrequire
– Adam
Apr 19 '17 at 9:20

add a comment |

up vote
1
down vote

Molomby's solution works in 2.4 and higher, but doesn't work with the current Debian version 2.2.22.

Ben's / Chris Heald's solutions also didn't work for me in 2.2.22, but that was due to a different order/satisfy configuration. These settings have changed with 2.4 and the solution seems to be incompatible with 2.4 and above (the redirect works, but the browser is just displaying an unauthorized error without asking for credentials).

Here is a combination of both solutions that should work for versions below and above 2.4:

RewriteEngine on
RewriteOptions Inherit # rewrite rules from parent directories
RewriteCond %{HTTPS} off
RewriteRule ^.*$ https://%{SERVER_NAME}%{REQUEST_URI} [R=301,L]

AuthType Digest
AuthName "private area"
AuthDigestProvider file
AuthUserFile /path/to/file/.htdigest

<IfVersion < 2.4>
Order Deny,Allow
Deny from all
Satisfy Any # reset this to 'All' in custom <Files> and <Directory> directives that block access
Allow from env=!HTTPS
Require valid-user
</IfVersion>
<IfVersion >= 2.4>
<If "%{HTTPS} == 'on'">
AuthMerging And
Require valid-user
</If>
</IfVersion>

Requirements: mod_rewrite, mod_auth, mod_digest, mod_version

share|improve this answer

answered Feb 19 '15 at 5:36

Istador

665

Nice thought, but it fails (500 error) because even with <IfVersion your script can't contain unknown commands like Configuration Sections (in v2.2). That's how it is in most if not all programming languages. This is where something like PHP's function_exists could have been handy.
– LWC
Aug 6 '17 at 21:09

@LWC 1.) Programming languages are a bad metaphor for your point. Counter example: invalid C code can be compiled, if a preprocessor removes the invalid sections. As an user I'd expect IfVersion to work similar without evaluating its content. 2.) I had this config in use from 2014-02 till 2014-09 with Apache 2.2.22. It might have been invalid and might have resulted in error log entries (I did not check), but it worked as expected and didn't responded with 5xx errors. (Maybe it only worked because of the Debian version, wich sometimes differentiates from the upstream version.)
– Istador
Aug 8 '17 at 19:14

I guess not all, just a lot of them. Thanks for the clarification!
– LWC
Aug 8 '17 at 23:29

add a comment |

up vote
1
down vote

I'm running Apache 2.2 and none of the above solutions worked for me. I found a workaround for me here. Basically, you need to set SSLRequireSSL and use some script language in the ErrorDocument to forward users to HTTPS. Unfortunately, in my case this only works when accessing particular files on the server, it does NOT work if just the domain is provided. Here is what I did:

AuthType Basic
AuthName "Password Protected Area"
AuthUserFile /my/path/to/.htpasswd
#Require valid-user

<FilesMatch "(^(?!ssl.php).*)">
SSLRequireSSL
ErrorDocument 403 /ssl.php
Require valid-user
</FilesMatch>

The regex in FileMatch tells apache to SSLRequireSSL for all files except ssl.php - and forward the user to ssl.php if he tries to access without SSL.

My ssl.php looks like this:

if(!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] == "" || $_SERVER['HTTPS'] == "off")
{
$redirect = "https://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
header("HTTP/1.1 301 Moved Permanently");
header("Location: $redirect");
exit;
}

What now happens:

Opening http://example.com/some/file.php forwards to
https://example.com/some/file.php and asks for username &
password.

Opening https://example.com/ connects via https and asks for u/p

Opening https://example.com/some/file.php does basically the same.

Opening http://example.com/ forwards to some default apache server page

The last point is what I am not happy with, if someone has a solution for that, I'd be glad to hear about it. Things I tried to solve this issue:

Changed the regular expression to (^$)|(^(?!ssl.php).*) to explicitly also match empty strings. Did not work

Added a rewrite rule to rewrite an empty string to index.php. Does not work either.

share|improve this answer

answered Dec 17 '15 at 9:41

user3205494

928

add a comment |

up vote
0
down vote

None of the above worked for me, but this did. My only concern is if there are certain conditions whereby the auth is not triggered allowing someone access without the credentials. I'm not sure there are, but maybe you bright people may say otherwise.

This code redirects non-www to www and http to https, with .htaccess folder auth.

This is the contents of the htaccess file in the directory you want to protect:

RewriteEngine on
# ensure www.
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}/foldername/$1 [L,R=301]
# ensure https
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteCond %{HTTPS} !=on [NC]
RewriteRule ^(.*)$ https://%{HTTP_HOST}/foldername/$1 [L,R=301]

# Apache 2.4 If
<If "%{HTTPS} == 'on' && %{HTTP_HOST} =~ /www/">
AuthType Basic
AuthName "Protected folder"
AuthUserFile "/home/etc/.htpasswds/public_html/foldername/passwd"
require valid-user
</If>

share|improve this answer

answered Feb 8 at 6:42

MarkApp

11

add a comment |

Your Answer

draft saved

draft discarded

Sign up or log in

Sign up using Google

Sign up using Facebook

Sign up using Email and Password

Post as a guest

Name

Email

Post Your Answer
Discard

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged apache .htaccess or ask your own question.

asked

6 years, 6 months ago

viewed

19,374 times

active

8 months ago

Linked

77

Adding comments to .htaccess

27

How to logout when using .htaccess (and .htpasswd) authentication?

4

Force SSL on Apache, with Auth and Canonical redirect

5

.htaccess, mod_rewrite, and basic authentication

7

Apache 2.2 redirect to SSL *then* do auth (with solution < but is it crap?)

3

How do I combine basic authentication and https?

1

How to rewrite before asing for authorization in htaccess?

0

Why isn't redirect done before authentication when using the L-flag?

Related

85
How to remove .htaccess password protection from a subdirectory

7
Do HTTP authentication over HTTPS with URL rewriting

1
http to https redirection using .htaccess not working

4
Force SSL on Apache, with Auth and Canonical redirect

3
Directory protection asking for password twice on my https website?

0
cloudflare user-agent in htaccess

1
How to always redirect to https://www and https://subdomain?

-2
Multi-site wordpress redirect between https subdomains via htaccess

1
Redirection from http to https is not working

1
Htaccess URLs redirects are working for http not all https

Hot Network Questions

Is my story pacing too fast?

How do variables in C++ store their type?

This is a picture on my LG TV screensaver. I would like to know where this is?

Can one detect from earth that angular momenta of its axial rotation and its orbital rotation are "almost parallel"?

Install Ubuntu on Alienware 15 R4

Can I eat only a crème brûlée in Paris?

Cannot mount sda1: "The device '/dev/sda1' doesn't seem to have a valid NTFS."

Ask him (about) the price of the car

Panel breakers are alternately 90 V and 140 V

How much alteration would be needed for the Cuban Missile Crisis to go nuclear?

Is there a single historic event which could be changed to cause the USA to use SI units?

Can you infer causality from correlation?

Fill everything except a circle in the middle of the plot

How can you write when you're upset?

Can 'nook' be used outside the saying 'nook and cranny'? Is it common?

good way to horizontally align enumerate items

Given a string, calculate the number of columns it corresponds to

How should I discuss about a paper with my potential supervisor who is one of the authors of that paper?

How to disable third party repositories in Ubuntu 16.04 LTS?

How to describe two knights defending each other?

Do antenna farms on spacecraft make any sense or are they purely aesthetic?

Conditional Probability --- Card Question

Is revving the engine to redline on idle at morning bad?

Why would mages not use mana they have stolen to permanently boost their power?

question feed

Stack Overflow

Questions

Jobs

Developer Jobs Directory

Salary Calculator

Help

Mobile

Disable Responsiveness

Products

Teams

Talent

Engagement

Enterprise

Company

About

Press

Work Here

Legal

Privacy Policy

Contact Us

Stack Exchange
Network

Technology

Life / Arts

Culture / Recreation

Science

Other

Stack Overflow

Server Fault

Super User

Web Applications

Ask Ubuntu

Webmasters

Game Development

TeX - LaTeX

Software Engineering

Unix & Linux

Ask Different (Apple)

WordPress Development

Geographic Information Systems

Electrical Engineering

Android Enthusiasts

Information Security

Database Administrators

Drupal Answers

SharePoint

User Experience

Mathematica

Salesforce

ExpressionEngine® Answers

Stack Overflow em Português

Blender

Network Engineering

Cryptography

Code Review

Magento

Software Recommendations

Signal Processing

Emacs

Raspberry Pi

Stack Overflow на русском

Programming Puzzles & Code Golf

Stack Overflow en español

Ethereum

Data Science

Arduino

Bitcoin

more (30)

Photography

Science Fiction & Fantasy

Graphic Design

Movies & TV

Music: Practice & Theory

Worldbuilding

Seasoned Advice (cooking)

Home Improvement

Personal Finance & Money

Academia

Law

more (15)

English Language & Usage

Skeptics

Mi Yodeya (Judaism)

Travel

Christianity

English Language Learners

Japanese Language

Arqade (gaming)

Bicycles

Role-playing Games

Anime & Manga

Puzzling

Motor Vehicle Maintenance & Repair

more (33)

MathOverflow

Mathematics

Cross Validated (stats)

Theoretical Computer Science

Physics

Chemistry

Biology

Computer Science

Philosophy

more (10)

Meta Stack Exchange

Stack Apps

API

Data

Area 51

Blog

Facebook

Twitter

LinkedIn

site design / logo © 2018 Stack Exchange Inc; user contributions licensed under cc by-sa 3.0
with attribution required.
rev 2018.10.19.31939