From 97aeda5678e594d515dbadb33450880c2674f6c6 Mon Sep 17 00:00:00 2001 From: Emilien Mantel Date: Mon, 14 Mar 2016 19:20:08 +0100 Subject: [PATCH] New feature: redirect_https (HTTP -> HTTPS) --- doc/vhost.md | 1 + templates/etc/nginx/sites-available/_base.j2 | 14 ++++++++++++++ tests/test.yml | 14 ++++++++++++++ 3 files changed, 29 insertions(+) diff --git a/doc/vhost.md b/doc/vhost.md index c0091f8..3d35956 100644 --- a/doc/vhost.md +++ b/doc/vhost.md @@ -16,6 +16,7 @@ Common - `redirect_from`: (O) Domain list to redirect to the first `name`. You can use this key to redirect non-www to www - `redirect_to`: (O) Redirect all requests to this domain. Please set scheme (http:// or https:// or $sheme). - `redirect_to_code`: Redirect code (default: 302) +- `redirect_https`: (O) Boolean. Redirect HTTP to HTTPS. - `location`: (O) Add new custom locations (it does not overwrite!) - `more`: (O) Add more custom infos. - `upstream_params`: (O) Add upstream params (useful when you want to pass variables to PHP) diff --git a/templates/etc/nginx/sites-available/_base.j2 b/templates/etc/nginx/sites-available/_base.j2 index 915793a..15128de 100644 --- a/templates/etc/nginx/sites-available/_base.j2 +++ b/templates/etc/nginx/sites-available/_base.j2 @@ -118,6 +118,20 @@ server { {% endif %} } +{% if item.redirect_https is defined and item.redirect_https %} +# +# Redirect HTTP to HTTPS +# +server { +{% for port in __listen %} + listen {{ port }}; +{% endfor %} + server_name {% if item.name is string %}{{ item.name }}{% else %}{{ item.name | join(' ') }}{% endif %}; + return 301 https://{{ __main_name }}{% if '443' not in __listen_ssl %}:__listen_ssl[0]{% endif %}/$request_uri; +} +{% endif %} + + {% if item.redirect_from is defined and item.redirect_from is iterable %} # # Redirect from diff --git a/tests/test.yml b/tests/test.yml index f341f71..479c255 100644 --- a/tests/test.yml +++ b/tests/test.yml @@ -172,6 +172,11 @@ ssl_name: 'test-ssl-predeployed.local' more: - 'add_header X-ansible-default 1;' + - name: 'test-ssl-redirect.local' + proto: ['https'] + template: '_base' + ssl_name: 'test-ssl.local' + redirect_https: true nginx_dh_length: 1024 roles: - ../../ @@ -289,6 +294,15 @@ with_items: - 'test-ssl-predeployed.local' - 'test-ssl.local' + - name: -- VERIFY SSL REDIRECT -- + command: "curl -v --insecure -H 'Host: {{ item }}' http://127.0.0.1/" + changed_when: false + register: sslredirok + failed_when: > + sslredirok.stderr.find('< Location') == -1 and + sslredirok.stderr.find('https://{{ item }}/') == -1 + with_items: + - 'test-ssl-redirect.local' # -------------------------------- # Default vhosts