Редирект с http на https, nginx

Я использую эту конфигурацию для nginx, я использую ее для sidecar в azure, следуя этому ссылка Не могу понять, что нужно изменить в настройках для автоматического перенаправления с http://domain на https://domain

# nginx Configuration File
# https://wiki.nginx.org/Configuration
# Run as a less privileged user for security reasons.
user nginx;
worker_processes auto;
events {
  worker_connections 1024;
}
pid        /var/run/nginx.pid;
http {
    #Redirect to https, using 307 instead of 301 to preserve post data
    server {
        listen [::]:443 ssl;
        listen 443 ssl;
        server_name localhost;
        # Protect against the BEAST attack by not using SSLv3 at all. If you need to support older browsers (IE6) you may need to add
        # SSLv3 to the list of protocols below.
        ssl_protocols              TLSv1.2;
        # Ciphers set to best allow protection from Beast, while providing forwarding secrecy, as defined by Mozilla - https://wiki.mozilla.org/Security/Server_Side_TLS#Nginx
        ssl_ciphers                ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-AES256-SHA256:DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:ECDHE-RSA-RC4-SHA:ECDHE-ECDSA-RC4-SHA:AES128:AES256:RC4-SHA:HIGH:!aNULL:!eNULL:!EXPORT:!DES:!3DES:!MD5:!PSK;
        ssl_prefer_server_ciphers  on;
        # Optimize TLS/SSL by caching session parameters for 10 minutes. This cuts down on the number of expensive TLS/SSL handshakes.
        # The handshake is the most CPU-intensive operation, and by default it is re-negotiated on every new/parallel connection.
        # By enabling a cache (of type "shared between all Nginx workers"), we tell the client to re-use the already negotiated state.
        # Further optimization can be achieved by raising keepalive_timeout, but that shouldn't be done unless you serve primarily HTTPS.
        ssl_session_cache    shared:SSL:10m; # a 1mb cache can hold about 4000 sessions, so we can hold 40000 sessions
        ssl_session_timeout  24h;
        # Use a higher keepalive timeout to reduce the need for repeated handshakes
        keepalive_timeout 300; # up from 75 secs default
        # remember the certificate for a year and automatically connect to HTTPS
        add_header Strict-Transport-Security 'max-age=31536000; includeSubDomains';
        ssl_certificate      /etc/nginx/ssl.crt;
        ssl_certificate_key  /etc/nginx/ssl.key;
        location / {
            proxy_pass http://localhost:80; # TODO: replace port if app listens on port other than 80
            proxy_set_header Connection "";
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $remote_addr;
        }
    }
}

РЕДАКТИРОВАТЬ: после предложения в первом ответе это не сработало, с добавлением двух блоков это было так:

# nginx Configuration File
# https://wiki.nginx.org/Configuration
# Run as a less privileged user for security reasons.
user nginx;
worker_processes auto;
events {
  worker_connections 1024;
}
pid        /var/run/nginx.pid;
http {
    #Redirect to https, using 307 instead of 301 to preserve post data
   server {
        # catch HTTP requests for all valid HTTP `Host` header values
        listen 80;
        listen [::]:80;
        server_name _; # list all your domain names here
        # do redirection to HTTPS
        return 301 https://$http_host$request_uri;
    }
    server {
        # default server listening on port 80
        # getting here means the HTTP `Host` header is missing or had an incorrect value
        listen 80 default_server;
        listen [::]:80 default_server;
        # close the connection immediately
        return 444;
    }
    server {
        listen [::]:443 ssl;
        listen 443 ssl;
        server_name localhost;
        # Protect against the BEAST attack by not using SSLv3 at all. If you need to support older browsers (IE6) you may need to add
        # SSLv3 to the list of protocols below.
        ssl_protocols              TLSv1.2;
        # Ciphers set to best allow protection from Beast, while providing forwarding secrecy, as defined by Mozilla - https://wiki.mozilla.org/Security/Server_Side_TLS#Nginx
        ssl_ciphers                ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-AES256-SHA256:DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:ECDHE-RSA-RC4-SHA:ECDHE-ECDSA-RC4-SHA:AES128:AES256:RC4-SHA:HIGH:!aNULL:!eNULL:!EXPORT:!DES:!3DES:!MD5:!PSK;
        ssl_prefer_server_ciphers  on;
        # Optimize TLS/SSL by caching session parameters for 10 minutes. This cuts down on the number of expensive TLS/SSL handshakes.
        # The handshake is the most CPU-intensive operation, and by default it is re-negotiated on every new/parallel connection.
        # By enabling a cache (of type "shared between all Nginx workers"), we tell the client to re-use the already negotiated state.
        # Further optimization can be achieved by raising keepalive_timeout, but that shouldn't be done unless you serve primarily HTTPS.
        ssl_session_cache    shared:SSL:10m; # a 1mb cache can hold about 4000 sessions, so we can hold 40000 sessions
        ssl_session_timeout  24h;
        # Use a higher keepalive timeout to reduce the need for repeated handshakes
        keepalive_timeout 300; # up from 75 secs default
        # remember the certificate for a year and automatically connect to HTTPS
        add_header Strict-Transport-Security 'max-age=31536000; includeSubDomains';
        ssl_certificate      /etc/nginx/ssl.crt;
        ssl_certificate_key  /etc/nginx/ssl.key;
        location / {
            proxy_pass http://localhost:80; # TODO: replace port if app listens on port other than 80
            proxy_set_header Connection "";
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $remote_addr;
        }
    }
}

person Шурбески Христијан    schedule 19.11.2020    source источник


Ответы (1)


Предлагаю использовать два дополнительных серверных блока:

server {
    # catch HTTP requests for all valid HTTP `Host` header values
    listen 80;
    listen [::]:80;
    server_name domain www.domain; # list all your domain names here
    # do redirection to HTTPS
    return 301 https://$http_host$request_uri;
}
server {
    # default server listening on port 80
    # getting here means the HTTP `Host` header is missing or had an incorrect value
    listen 80 default_server;
    listen [::]:80 default_server;
    # close the connection immediately
    return 444;
}

Проверьте этот ответ для получения дополнительной информации об этой конфигурации.

Обновить

Проверка документации ссылка данный OP выглядит так, как в приведенном примере используется контейнер nginx, прослушивающий порт 443, выполняющий задание шифрования TLS и прокси-запросы к некоторому контейнеру примера Hello World, который прослушивает порт 80. Чтобы выполнить перенаправление HTTP на HTTPS через контейнер nginx, вы можете попробовать измените порт прослушивания контейнера примера Hello World на 8080 и заставьте nginx проксировать входящие запросы на этот порт вместо порта 80. Попробуйте следующую конфигурацию:

nginx.conf

# nginx Configuration File
# https://wiki.nginx.org/Configuration
# Run as a less privileged user for security reasons.
user nginx;
worker_processes auto;
events {
  worker_connections 1024;
}
pid        /var/run/nginx.pid;
http {
    #Redirect to https, using 307 instead of 301 to preserve post data
   server {
        # catch HTTP requests for all valid HTTP `Host` header values
        listen 80;
        listen [::]:80;
        server_name _; # list all your domain names here
        # do redirection to HTTPS
        return 307 https://$http_host$request_uri;
    }
    server {
        # default server listening on port 80
        # getting here means the HTTP `Host` header is missing or had an incorrect value
        listen 80 default_server;
        listen [::]:80 default_server;
        # close the connection immediately
        return 444;
    }
    server {
        listen [::]:443 ssl;
        listen 443 ssl;
        server_name localhost;
        # Protect against the BEAST attack by not using SSLv3 at all. If you need to support older browsers (IE6) you may need to add
        # SSLv3 to the list of protocols below.
        ssl_protocols              TLSv1.2;
        # Ciphers set to best allow protection from Beast, while providing forwarding secrecy, as defined by Mozilla - https://wiki.mozilla.org/Security/Server_Side_TLS#Nginx
        ssl_ciphers                ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AESGCM:ECDHE-RSA-AES128-SHA256:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA:ECDHE-ECDSA-AES128-SHA:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA:ECDHE-ECDSA-AES256-SHA:DHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA256:DHE-RSA-AES256-SHA256:DHE-DSS-AES256-SHA:DHE-RSA-AES256-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:ECDHE-RSA-RC4-SHA:ECDHE-ECDSA-RC4-SHA:AES128:AES256:RC4-SHA:HIGH:!aNULL:!eNULL:!EXPORT:!DES:!3DES:!MD5:!PSK;
        ssl_prefer_server_ciphers  on;
        # Optimize TLS/SSL by caching session parameters for 10 minutes. This cuts down on the number of expensive TLS/SSL handshakes.
        # The handshake is the most CPU-intensive operation, and by default it is re-negotiated on every new/parallel connection.
        # By enabling a cache (of type "shared between all Nginx workers"), we tell the client to re-use the already negotiated state.
        # Further optimization can be achieved by raising keepalive_timeout, but that shouldn't be done unless you serve primarily HTTPS.
        ssl_session_cache    shared:SSL:10m; # a 1mb cache can hold about 4000 sessions, so we can hold 40000 sessions
        ssl_session_timeout  24h;
        # Use a higher keepalive timeout to reduce the need for repeated handshakes
        keepalive_timeout 300; # up from 75 secs default
        # remember the certificate for a year and automatically connect to HTTPS
        add_header Strict-Transport-Security 'max-age=31536000; includeSubDomains';
        ssl_certificate      /etc/nginx/ssl.crt;
        ssl_certificate_key  /etc/nginx/ssl.key;
        location / {
            proxy_pass http://localhost:8080;
            proxy_set_header Connection "";
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $remote_addr;
        }
    }
}

deploy-aci.yaml

api-version: 2019-12-01
location: westus
name: app-with-ssl
properties:
  containers:
  - name: nginx-with-ssl
    properties:
      image: nginx
      ports:
      - port: 80
        protocol: TCP
      - port: 443
        protocol: TCP
      resources:
        requests:
          cpu: 1.0
          memoryInGB: 1.5
      volumeMounts:
      - name: nginx-config
        mountPath: /etc/nginx
  - name: my-app
    properties:
      image: mcr.microsoft.com/azuredocs/aci-helloworld
      ports:
      - port: 8080
        protocol: TCP
      resources:
        requests:
          cpu: 1.0
          memoryInGB: 1.5
  volumes:
  - secret:
      ssl.crt: <Enter contents of base64-ssl.crt here>
      ssl.key: <Enter contents of base64-ssl.key here>
      nginx.conf: <Enter contents of base64-nginx.conf here>
    name: nginx-config
  ipAddress:
    ports:
    - port: 80
      protocol: TCP
    - port: 443
      protocol: TCP
    type: Public
  osType: Linux
tags: null
type: Microsoft.ContainerInstance/containerGroups
person Ivan Shatsky    schedule 19.11.2020
comment
это не сработало, мне нужно взять эти два блока из блока http { } ? Я редактирую вопрос, чтобы вы могли видеть - person Шурбески Христијан; 19.11.2020
comment
Нет, они должны быть в контексте http. Это что-то связанное с лазурью. Я не знаком с azure, но по вашей ссылке я вижу пример, в котором используются два разных контейнера: один nginx прослушивает порт 443, а что-то с именем mcr.microsoft.com/azuredocs/aci-helloworld прослушивает порт 80. Чтобы сделать приведенную выше конфигурацию работоспособной, ваш контейнер nginx должен прослушивать оба 80 и 443 порта. - person Ivan Shatsky; 19.11.2020
comment
@ШурбескиХристијан Проверьте обновление ответа (это всего лишь предположение, но я думаю, что у него большие шансы сработать). Обновление Нет, скорее всего, чтобы сделать его работоспособным, вы должны заставить контейнер mcr.microsoft.com/azuredocs/aci-helloworld прослушивать порт 8080 вместо 80. - person Ivan Shatsky; 20.11.2020
comment
@ШурбескиХристијан Согласно этому информационное несимметричное сопоставление портов не поддерживается Azure (и вообще не планируется), поэтому ACI Hello World не подходит для проверки перенаправления с HTTP на HTTPS. Однако его файл index.js содержит var listener = app.listen(process.env.PORT || 80, ... строку (продолжение следует) - person Ivan Shatsky; 20.11.2020
comment
@ШурбескиХристијан, что означает, что вы можете изменить порт прослушивания с помощью переменной среды PORT, но я не знаю, как это можно сделать с контейнерами Azure. - person Ivan Shatsky; 20.11.2020