ericg
ericg

Reputation: 103

In Pyramid how can I redirect from http to https?

If you don't have access to the webserver, and the only way you have is to intercept the request and then do a redirect from http to https, what is the best approach to redirect?

I tried looking at subscribers using NewRequest. I did something like so:

@subscriber(NewRequest)
def modify_protocol(event):
    if re.search('some string', event.request.host_url):
        event.request.scheme = 'https'

However, this didn't do what I expected. The page is still being rendered. Any ideas would be appreciated.

Thanks in advance.

Upvotes: 3

Views: 2268

Answers (2)

imsky
imsky

Reputation: 3279

Inside a view:

if req.scheme == "http":
        return HTTPFound("https://" + req.host + req.path_qs)

Using an event listener:

@subscriber(NewRequest)
def redirect(event):
    if event.request.scheme == "http":
        raise HTTPFound("https://" + event.request.host + event.request.path_qs)

I looked into approaches using send and get_response, but couldn't find much.

Upvotes: 7

synthesizerpatel
synthesizerpatel

Reputation: 28036

Some unsolicited advice - Don't redirect to SSL from non-SSL.

There's a security issue. Basically, if someone manages to Man-In-The-Middle your non-SSL'd service, they could redirect it to an SSL service running with a valid certificate on a different server - the user might not notice this.

It's better to provide a page that warns the user and provides a plain-text link for them to click.

Upvotes: 0

Related Questions