如何从 nginx 中的根位置进行重定向而不阻止访问子位置?

如何从 nginx 中的根位置进行重定向而不阻止访问子位置?

如何让 nginx 仅在请求根路径时重定向到另一个路径?

这是我的服务器配置的一部分:

server {
        listen     80; ## listen for ipv4; this line is default and implied
    #listen   [::]:80 default_server ipv6only=on; ## listen for ipv6

    # Make site accessible from http://localhost/
    server_name wiki wiki.leerdomain.lan;

    # Note: There should never be more than one root in a 
    #       virutal host
    #   Also there should never be a root in the location.
    #root /var/www/nginx/;

    rewrite ^/$ /rootWiki/ redirect; 


    location ^~ /rootWiki/ {
            resolver 127.0.0.1 valid=300s;
            access_log ./logs/RootWiki_access.log;
            error_log ./logs/RootWiki_error.log;
            proxy_buffers 16 4k;
            proxy_buffer_size 2k;
            proxy_set_header Host $host;
            proxy_set_header X-Real_IP $remote_addr;
            rewrite /rootWiki/(.*) /$1 break;
            proxy_pass http://192.168.1.200:8080;
        }

   location ^~ /usmle/ {
    access_log ./logs/usmle_access.log;

 ...

当我按照上面的方式配置它时,我无法访问 root 下的任何子位置...但是根目录确实转发到,/rootWiki/但我502 Bad Gateway在端口 8080 上收到了一个而不是应用程序。

当我删除该行时:

rewrite ^/$ /rootWiki/ redirect;

我能够访问 rootWiki 应用程序,以及 root 的所有子位置都很好。

在我看来,它应该有效,但似乎没有。

答案1

让我们用独立的“位置”指令来分隔您的配置:

# location for pure root path with trailing EOL
location ~ ^/$ {
    # Redirect only when we have no one
    # argument like www.example.com/?user=name for example 
    if ($is_args = "") {
        rewrite ^/$ /rootWiki/ redirect; 
    }
}

# After above "location" directive you can use even
# static files for the root path or subfolders.
# For examle:
# www.example.com/index.html
# www.example.com/user/general.html
location / {
    root /var/www/www.example.com/static/;
    index index.html;
}

location ^~ /rootWiki/ {
    resolver 127.0.0.1 valid=300s;
    access_log ./logs/RootWiki_access.log;
    error_log ./logs/RootWiki_error.log;
    proxy_buffers 16 4k;
    proxy_buffer_size 2k;
    proxy_set_header Host $host;
    proxy_set_header X-Real_IP $remote_addr;
    rewrite /rootWiki/(.*) /$1 break;
    proxy_pass http://192.168.1.200:8080;
}

location ^~ /usmle/ {
    access_log ./logs/usmle_access.log;
}

相关内容