nginx https自动重定向到特定端口

nginx https自动重定向到特定端口

我不确定主题是否正确地概括了我的问题但我会尽力解释它。

我的服务器中有以下配置,该服务器有 2 个虚拟主机:example.com 和 meudomain.com

第一个 vhost 需要监听 8080 (https),​​正如你所见,我正在使用从 http > https 8080 的重定向。第二个正在监听 80。

我的问题是,如果用户在地址栏中输入 https 而不是 http,它会调用第二个 vhost。

如何重定向https://example.comhttps://example.com:8080代替http://meudomain.com当用户在地址栏中输入 https 时?

server {
    listen 80;
    server_name example.com;
    location '/.well-known/acme-challenge/' {
        autoindex on;
        root /var/www/certbot;
    }

    location / {
        if ($scheme = http) {
            return 301 https://example.com:8080;
        }
   }
}

server {
    listen 8080 default ssl;
    server_name example.com;
    ssl_certificate /etc/letsencrypt/live/example.com;/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; # managed by Certbot

    # logs
    error_log /var/log/nginx/example.com_error.log error;
    access_log /var/log/nginx/example.com_access.log;

    location / {
        index  index.html index.htm;
        autoindex on;
        proxy_pass http://internalserver:8080;
        auth_basic      "Restricted area";
        auth_basic_user_file /srv/example.com/.htpasswd;
        client_body_temp_path /tmp 1 2;
        client_body_buffer_size 256k;
        client_body_in_file_only off;
    }
}

答案1

只需添加此服务器块即可重定向所有https://example.comhttps://example.com:8080

server {
        listen 443 ssl;
        ssl_certificate /etc/letsencrypt/live/example.com;/fullchain.pem; # managed by Certbot
        ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; # managed by Certbot
        return 301 https://example.com:8080$request_uri;
}

答案2

请记住,当用户简单地输入https://example.com在地址栏中,浏览器会采用默认 SSL 端口(端口 443)。您实际上并没有在配置中处理该端口,您必须从侦听该端口的服务器进行重定向。您可以在此处执行此操作:如何在非标准端口上运行 nginx SSL

相关内容