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

Eli*_*aul 4 nginx reverse-proxy 301-redirect

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

所以例如

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

https://example.com -> https://example.com/subdirectory
Run Code Online (Sandbox Code Playgroud)

这在我看来很简单,但我正在努力实现这一目标。我试过使用重写的变体并返回 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;
    }
Run Code Online (Sandbox Code Playgroud)

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

Ter*_*nen 8

此配置将执行您想要的操作:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

= /说明符意味着完全匹配,所以它仅确切根URI相匹配的虚拟服务器的。