nginx实现301跳转问题,跳转后访问变成404?

配置如下:

server {
#     listen *:8080;
#     listen [::]:8080;
    listen *:80;
    listen [::]:80;

    server_name test.vv.com;
    header_filter_by_lua_file /etc/nginx/lua/logmerge.lua;

    set $cache_server "cacheserver";
    set $cpid '-';   

    index index.html index.htm index.php;
    access_log /var/log/nginx/static-website.access.log hycdnex;
    error_log /var/log/nginx/static-website.error.log info;

    location /cyum {
        proxy_pass http://cacheserver;
        proxy_read_timeout 120;
        proxy_connect_timeout 90;
        proxy_redirect off;
        proxy_http_version 1.1;

        proxy_set_header Connection "";
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-From-IP $remote_addr;
        proxy_intercept_errors on;
        error_page 301 = @error_page_302;
        error_page 302 = @error_page_302;
        error_page 303 = @error_page_302;
        error_page 307 = @error_page_302; 
    }

    location /anolis {
        proxy_pass http://$cache_server;
        proxy_read_timeout 120;
        proxy_connect_timeout 90;
        proxy_redirect off;
        proxy_http_version 1.1;

        proxy_set_header Connection "";
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-From-IP $remote_addr;
    }
    
    location @error_page_302 {
        resolver   117.136.194.211 39.135.2.193 114.114.114.114;
        set        $duri  "";
        if ($upstream_http_location ~* "http://(.*)") {set $duri http://$1;}
        if ($upstream_http_location ~* "https://(.*)") {set $duri https://$1;}
        #proxy_pass              http://$duri;
        proxy_pass            $duri;
        proxy_read_timeout    120;
        proxy_connect_timeout 90;
        proxy_http_version    1.1;
        proxy_set_header      Connection "";
        proxy_set_header      X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header      X-From-IP $remote_addr;
        proxy_force_ranges    on;
        proxy_set_header      Proxy '';
  }

    send_timeout 300s;
}

cache_server表示ats,里面代理的源站有301,301回来后在nginx用301的Location的url发起请求,但是,后续请求变成404

阅读 1.8k
1 个回答

可能是因为你在@error_page_302 location中有一个if语句,而nginx的if语句是不推荐使用的,可能会导致一些奇怪的行为。你可以尝试将if语句替换为更安全的map指令。

另外,你也可以检查一下proxy_pass设置的url是否正确,你可以在@error_page_302 location中添加error_log,并观察日志中是否有关于proxy_pass的错误信息。

你可以尝试将@error_page_302 location中的if语句替换为以下的map指令:

map $upstream_http_location $duri {
    ......
    ~(http://.*)  $1;
    ~(https://.*) $1;
    ......
}

别忘了重启nginx服务,使配置生效。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏