Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force SSL on Apache, with Auth and Canonical redirect

I've read some posts on how to redirect to SSL, also some on how to make sure a site is using the www subdomain / canonical name, and some on how to set up Basic Auth. Here is what I have in my .htaccess file right now:

RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]


RewriteEngine on
RewriteCond %{HTTP_HOST} !(^www\.site\.com*)$
RewriteRule (.*) https://www.site.com$1 [R=301,L]


AuthName "Locked"
AuthUserFile "/home/.htpasswd"
AuthType Basic
require valid-user

It works fairly well, but I'd like to optimize it. My questions include:

  1. How do I avoid double authentication? When I access the site w.o. SSL I have to authenticate, and then I am redirected to SSL and have to authenticate again. Can I just be redirected and then authenticated?
  2. It looks like the first rule is pretty awesome because I could use it on any site without modifying it. Can rule #2 be rewritten to be site-independent? ie: it will force www to be used on any site no matter what the domain name is (with a better written rule)? answered here
  3. How would I do the reverse of number 3 with a rule that would work on any site to force the site not to use www, ie redirect to site.com from www.site.com? answered here
like image 745
cwd Avatar asked Dec 21 '22 18:12

cwd


2 Answers

For #1

How to avoid double authentication? Can I just be redirected and then authenticated?

Boom! This works.

SSLOptions +StrictRequire
SSLRequireSSL
SSLRequire %{HTTP_HOST} eq "www.askapache.com"
ErrorDocument 403 https://www.askapache.com/admin/

See:

  • http://www.askapache.com/htaccess/apache-ssl-in-htaccess-examples.html
  • http://www.askapache.com/htaccess/ssl-example-usage-in-htaccess.html
  • http://www.askapache.com/htaccess/htaccess.html

Just put that above block at the top of your .htaccess, here is mine:

SSLOptions +StrictRequire
SSLRequireSSL
SSLRequire %{HTTP_HOST} eq "www.askapache.com"
ErrorDocument 403 https://www.askapache.com/admin/

AuthType Digest
AuthName "Protected By AskApache"
AuthDigestDomain / https://www.askapache.com/admin/
AuthUserFile /home/askapache/.htpasswd-digest
Require valid-user
Satisfy All
like image 137
AskApache Webmaster Avatar answered Dec 28 '22 09:12

AskApache Webmaster


If you're using Apache 2.4 you can also avoiding the double authentication using configuration sections.

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

# Authenticate users only when using HTTPS
<If "%{HTTPS} == 'on'">
    AuthType Basic
    AuthName "Special things"
    AuthUserFile /etc/blah.htpasswd
    Require valid-user
</If>

I've given a more refined version of this in my answer here.

like image 42
Molomby Avatar answered Dec 28 '22 11:12

Molomby