Nginx 自动将子域名的 HTTP 重定向到 HTTPS

Nginx 自动将子域名的 HTTP 重定向到 HTTPS

我正在尝试自动将所有流量从 重定向httphttps。如何对我的所有域和子域进行 301 重定向?

这是 NGNIX 配置文件

upstream app_server {
    server unix:/run/DigitalOceanOneClick/unicorn.sock fail_timeout=0;
}

server {
        listen 80 default_server;
        listen [::]:80 default_server;
        server_name sprintsocial.io app.sprintsocial.io admin.sprintsocial.io;
#       return 301 https://$server_name$request_uri;
}

server {
    #listen   80;
    listen 443;
    root /home/rails/sprintsocial/public;
    #server_name _;
    server_name sprintsocial.io app.sprintsocial.io admin.sprintsocial.io;
    ssl on;
    ssl_certificate /home/sprintsocial.io.chained.crt;
    ssl_certificate_key /home/sprintsocial.io.key;
    index index.htm index.html;
#    return 301 https://$server_name$request_uri;

#    rewrite ^/(.*) https://app.sprintsocial.io/$1 permanent;
#    rewrite ^/(.*) https://admin.sprintsocial.io/$1 permanent;

    location / {
            try_files $uri/index.html $uri.html $uri @app;
    }

    location ~* ^.+\.(jpg|jpeg|gif|png|ico|zip|tgz|gz|rar|bz2|doc|xls|exe|pdf|ppt|txt|tar|mid|midi|wav|bmp|rtf|mp3|flv|mpeg|avi)$ {
                    try_files $uri @app;
            }

     location @app {
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header Host $http_host;
            proxy_redirect off;
            proxy_pass http://app_server;
    }
}

答案1

你应该能够这样做:

server {
    listen [::]:80 default_server ipv6only=off;
    server_name sprintsocial.io app.sprintsocial.io admin.sprintsocial.io;
    return 301 https://$host$request_uri;
}

请注意:

  • listen [::]:80 ipv6only=off同时绑定到 ipv4 和 ipv6,
  • $host变量来自请求,$server_name来自server处理请求的变量,差别很大
  • 当与请求匹配时,它将被其他server指令否决server_name

相关内容