.htaccess seemingly ignored on OpenShift

2019-06-25 11:47发布

问题:

I'm working on a site on OpenShift (Django, Python 2.7, Apache), and I'd like it to always be served over HTTPS. I figured this would be a simple task using .htaccess, and OpenShift's knowledge base seems to show that it should be. However, I've been agonizing over this for days, and I can't figure out how to make it work. Basically, I can't get my .htaccess files to operate on anything but static files. I simply can't get requests for non-static resources to redirect to anything.

Here's my directory structure, inside ~/app-root/repo. It's using the "new" (March 2014 or so?) OpenShift directory structure.

/MyProject
    settings.py
    urls.py
    [etc.]
/[app directories]
/static
/wsgi
    wsgi.py
    static -> ../static
manage.py
requirements.txt

Ok, so after much frustration, I've been testing with a minimum viable .htaccess to just see if I can get anything to work. It looks like this:

RewriteEngine on
RewriteRule .* http://www.google.com

Everything should go to Google. If I put this in the wsgi directory, all my static files get redirected to google.com, but nothing else does. If I put it in ~/app-root/repo, nothing at all happens. It's like the file doesn't exist.

Similarly, if I use the commands suggested by OpenShift and put the file in wsgi, my static files get redirected to use HTTPS, but nothing else does.

I've also tried WSGI and Django things like adding os.environ['HTTPS'] = "on" to wsgi.py as suggested by sites like this one. That's been ineffective, and I really can't say I'm knowledgable enough about those sorts of settings to know what I'd need to add, but ideally I'd like to do this through .htaccess. The request should be using SSL before it hits WSGI.

What do I need to do to make my .htaccess files work on all requests? And why is OpenShift ignoring .htaccess files not in wsgi?

回答1:

I fought with this for a short time and quickly decided to use the django-ssl-redirect middleware package.

The whole reason I'm on OpenShift is to avoid fighting with these kinds of configuration issue, so I'm a little disappointed I had to resort to this.

Still, here goes:

Just add this to your MIDDLEWARE_CLASSES

'ssl_redirect.middleware.SSLRedirectMiddleware',

Add this to requirements.txt

django-ssl-redirect==1.0

Add something like this in settings (I put this in my base settings file that I share in multiple environments, hence the "if").

if os.environ.has_key('OPENSHIFT_REPO_DIR'):
    SSL_ON = True
    SSL_ALWAYS = True

More info here: https://bitbucket.org/nextscreenlabs/django-ssl-redirect