Combine URL rewriting (to force https) with http auth?
-
23-09-2019 - |
Question
I have a domain, mattpotts.com
and have set up a sub-domain dev.mattpotts.com
for me to develop on and will then copy the files to the normal domain when they're ready to go.
My directory structure is as follows and dev.mattpotts.com
points to dev/
+-public_html/ +-project1/ +-project2/ +-project3/ +-dev/ +-project1 +-project2 +-project3
I basically want to be able to go from http://mattpotts.com/project1
to https://dev.mattpotts.com/project1
by adding dev.
.
I have the following .htaccess
in dev/
and it works, all this needs to do is force https.
RewriteEngine On RewriteCond %{SERVER_PORT} 80 RewriteCond %{REQUEST_URI} dev RewriteRule ^(.*)$ https://dev.mattpotts.com$1 [R,L]
I want to force https so that I can securely use http auth on the directory. However, when I combine it with the following rules, it doesn't work. I have my .htpasswd
set up but I've not even had the login form show up yet.
AuthType Basic AuthName "Dev Protected Area" AuthUserFile .htpasswd Require valid-user
How can I successfully combine the to set of .htaccess
rules?
Edit, very strange things are happening!
https://dev.mattpotts.com/project1/ displays 'hello!' from non dev version of site (note https) http://dev.mattpotts.com/project1/ displays 'hello dev!' (as desired) from dev version. What's going on here?!
Solution
You've told us where your .htaccess
file is, but you haven't told us where your .htpasswd
file is. According to the Apache documentation on AuthUserFile:
Syntax: AuthUserFile file-path
File-path is the path to the user file. If it is not absolute (i.e., if it doesn't begin with a slash), it is treated as relative to the
ServerRoot
.
So in other words, it is looking for the .htpasswd
in somewhere like /etc/apache2/.htpasswd
. So either move your .htpasswd
file there, or make your directive contain an absolute path to the file, e.g.:
AuthType Basic
AuthName "Dev Protected Area"
AuthUserFile /home/mattpots.com/public_html/dev/.htpasswd
Require valid-user
However, for security reasons, I highly recommend keeping your .htpasswd
file outside of your document root.
OTHER TIPS
These issues should be independent of each other: do I understand correctly that the "force HTTPS" part works?
That said, AuthUserFile .htpasswd
may be looking for .htpasswd in the wrong place. The easiest fix is to put the full path and name there, e.g. AuthUserFile /home/matt/www/public_html/dev/.htpasswd
(or wherever you have the dev directory).