Nginx

強制從 http 重定向到 https nginx 到特定埠

  • September 30, 2019

我有一個在 9000 埠上執行的服務並使用letsencrypt 設置ssl。我想將所有請求從 http 轉發到 https。

http://demo.mydomain.com -> https://demo.mydomain.com 
http://www.demo.mydomain.com -> https://demo.mydomain.com 
www.demo.mydomain.com -> https://demo.mydomain.com

這是我的配置

vi /etc/nginx/sites-available/default

server {
       root /var/www/html;

       server_name demo.mydomain.com;

       location / {
               proxy_pass http://127.0.0.1:9000;
               proxy_http_version 1.1;
               proxy_set_header Upgrade $http_upgrade;
               proxy_set_header Connection 'upgrade';
               proxy_set_header Host $host;
               proxy_cache_bypass $http_upgrade;
       }


   listen [::]:443 ssl ipv6only=on; # managed by Certbot
   listen 443 ssl; # managed by Certbot
   ssl_certificate /etc/letsencrypt/live/demo.mydomain.com/fullchain.pem; # managed by Certbot
   ssl_certificate_key /etc/letsencrypt/live/demo.mydomain.com/privkey.pem; # managed by Certbot
   include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
   ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot

}



server {
   if ($host = demo.mydomain.com) {
       return 301 https://$host$request_uri;
   } # managed by Certbot

    listen 80 default_server;
    listen [::]:80 default_server;

    server_name demo.mydomain.com;
    return 301 https://$host$request_uri;
    #return 404; # managed by Certbot

}

nginx -t

systemctl 重新載入 nginx.service

curl -I https://demo.mydomain.com -> 可以

curl -I http://demo.mydomain.com -> 超時

我嘗試了許多類似的解決方案,但對我沒有任何效果。感謝您提供任何線索。

這是我愚蠢的錯誤。在 aws 實例中未打開埠 80。但是,對於在不同埠中執行的服務,這是從 http 強制重定向到 https 的工作配置。

server {
       server_name demo.mydomain.com www.demo.mydomain.com;

       location / {
               proxy_pass http://127.0.0.1:9000;
               proxy_http_version 1.1;
               proxy_set_header Upgrade $http_upgrade;
               proxy_set_header Connection 'upgrade';
               proxy_set_header Host $host;
               proxy_cache_bypass $http_upgrade;
       }

   listen [::]:443 ssl ipv6only=on; # managed by Certbot
   listen 443 ssl; # managed by Certbot
   ssl_certificate /etc/letsencrypt/live/demo.mydomain.com/fullchain.pem; # managed by Certbot
   ssl_certificate_key /etc/letsencrypt/live/demo.mydomain.com/privkey.pem; # managed by Certbot
   include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
   ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
}

server {
   if ($host = demo.mydomain.com) {
       return 301 https://$host$request_uri;
   } # managed by Certbot

    listen 80 default_server;
    listen [::]:80 default_server;

    server_name demo.mydomain.com;
    #return 404; # managed by Certbot
}

還要確保打開埠 80 和 443。乾杯!

引用自:https://serverfault.com/questions/985632