Nginx:将 http 和 https 根目录重定向到子目录

Nginx:将 http 和 https 根目录重定向到子目录

我正在尝试将 nginx 中 http 和 https 的根域重定向到同一个子目录(https):

例如

http://example.com -> https://example.com/subdirectory

https://example.com -> https://example.com/subdirectory

虽然这对我来说很简单,但我却很难实现。我尝试过使用各种重写并返回 301,但总是以重定向循环告终。

我当前的配置(导致循环):

server {
        listen      80;
        server_name example.com;
        return 301 https://$server_name/subdirectory;
        }
server {
        listen 443 ssl spdy;
        server_name example.com;
        return 301 https://$server_name/subdirectory;
    }

所以基本上,我试图从根域重定向到 https 上的同一个子目录,无论根域是通过 http 还是 https 请求的。

答案1

此配置将完成您想要的操作:

server {
    listen 80;
    server_name example.com;

    return 301 https://$server_name/subdirectory;
}

server {
    listen 443;
    server_name example.com;

    location = / {
        return 301 https://$server_name/subdirectory;
    }
}

= /说明符表示完全匹配,因此它仅匹配虚拟服务器的精确根 URI。

答案2

显然,如果您不从 ssl vhost 的此行为中排除位置子目录,它将不起作用。

server {

    listen 80;
    server_name example.com;

    return 301 https://$server_name/subdirectory;

}

server {

    listen 443 ssl spdy;
    server_name example.com;

    location /subdirectory {
        # Your stuff
    }

    location = / {
        return 301 https://$server_name/subdirectory;
    }

}

答案3

server {
    listen 80:
    server_name example.com;

    return 301 https://$server_name/subdirectory/;
}

server {
    listen 443;
    server_name example.com;

    location = / {
        return 301 https://$server_name/subdirectory/;   
    }
}

看看我是如何在末尾添加斜杠的,这非常重要,否则您将得到重定向循环。

答案4

另一种方法有一些“调整”......

server {
    access_log /var/log/nginx/<DOMAIN_NAME>-access.log;
    error_log /var/log/nginx/<DOMAIN_NAME>-error.log;
    listen <PORT_PROXY>;
    server_name <DOMAIN_NAME>;

    location /<SUBDIRECTORY> {
        proxy_pass http://<RESOURCE_IP>:<RESOURCE_PORT>/<SUBDIRECTORY>;
        proxy_redirect off;
        proxy_set_header Host $host:<PORT_PROXY>;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Real-IP $remote_addr;
    }

    location = / {
        return 301 https://$server_name/<SUBDIRECTORY>;
    }

}

谢谢!=D

相关内容