Nginx 使用子路径反代理网站

主域名: www.gxtest.com
主网站: http://127.0.0.1:8090
子网站: http://127.0.0.1:8604
将子网站映射到主网站的 /Attachment 目录。

server {
    #监听443端口
    listen       443;
    #对应的域名
    server_name www.gxtest.com;
    ssl on;
    
    ssl_certificate C:/nginx-1.23.1/ssl/cusssl.pem;        
    ssl_certificate_key C:/nginx-1.23.1/ssl/cusssl.key;

    ssl_ciphers EECDH+CHACHA20:EECDH+CHACHA20-draft:EECDH+AES128:RSA+AES128:EECDH+AES256:RSA+AES256::!MD5;
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;

    ssl_session_cache shared:SSL:10m;

    ssl_stapling on;
    ssl_stapling_verify on;
    resolver 8.8.4.4 8.8.8.8 valid=300s;
    resolver_timeout 5s;

    ssl_prefer_server_ciphers on;
    ssl_dhparam C:/nginx-1.23.1/ssl/dhparam.pem;

    add_header Strict-Transport-Security "max-age=31536000";
    add_header Content-Security-Policy "upgrade-insecure-requests;connect-src *";

    location / {
        proxy_pass http://127.0.0.1:8090;
        proxy_redirect http:// $scheme://;
        proxy_set_header Host $host:$server_port;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

        # 设置变量来实现 if 嵌套判断            
        set $flag "0";
        # 根据 referer 头判断是否是从子网站的请求
        if ($http_referer ~ ^https?://[\w\.:]*/Attachment.*) {
            set $flag "1";
        }
        if ($request_method ~* ^(GET)$ ) {
            set $flag "${flag}1";                
        }
        if ($request_method !~* ^(GET)$ ) {
            set $flag "${flag}0";                
        }
        # 来自 Attachment 的 GET 请求跳转
        if ($flag = "11") {
            rewrite (.+) $scheme://$host:$server_port/Attachment$1 permanent;
        }
        # 来自 Attachment 的非 GET 请求转发到子网站
        if ($flag = "10") {
            proxy_pass http://127.0.0.1:8604;
        }
    }

    location /Attachment/ {
        proxy_pass http://127.0.0.1:8604/;
        # 静态文件的输出路径替换
        sub_filter '="/Content/' '="/Attachment/Content/';
        sub_filter ':"/Content/' ':"/Attachment/Content/';
        sub_filter_types *;
        sub_filter_once off;
        # 根目录替换为子目录
        proxy_redirect / /Attachment/;
        
        proxy_set_header Host $host:$server_port;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
}
Nginx

我来吐槽

*

*