如何从/到/index.html代理传递

How to Proxy Pass from / to /index.html

我目前正在开发一个使用 url 路径的 JS 项目。现在,如果我使用 example.com/ 访问我的网站,JavaScript 将不起作用,因为我实际上需要示例。com/index.html

我已经在使用反向代理来代理传递给两个不同的 docker 容器。所以我的想法是当 [= 时将请求传递给 example.com/index.html 21=]example.com/ 被调用。但是我想不出实现这个目标的正则表达式。

我的旧配置:

server {
listen       80;
server_name  example.com;

# allow large uploads of files - refer to nginx documentation
client_max_body_size 1G;

# optimize downloading files larger than 1G - refer to nginx doc 
before adjusting
#proxy_max_temp_file_size 2G;

location / {
    proxy_pass http://structure.example:80;
}

location /cdn {
    proxy_pass http://content.example:80;
}

error_page   500 502 503 504  /50x.html;
location = /50x.html {
    root   /usr/share/nginx/html;
}

}

我试过的东西:

    server {
listen       80;
server_name  example.com;

# allow large uploads of files - refer to nginx documentation
client_max_body_size 1G;

# optimize downloading files larger than 1G - refer to nginx doc 
before adjusting
#proxy_max_temp_file_size 2G;

location / {
    proxy_pass http://structure.nocms:80/index.html;
}

location ~* \S+ {
    proxy_pass http://structure.nocms:80;
}

location /cdn {
    proxy_pass http://content.nocms:80;
}



error_page   500 502 503 504  /50x.html;
location = /50x.html {
    root   /usr/share/nginx/html;
}

}

以下配置应该适合您

server {
listen       80;
server_name  example.com;

# allow large uploads of files - refer to nginx documentation
client_max_body_size 1G;

# optimize downloading files larger than 1G - refer to nginx doc 
before adjusting
#proxy_max_temp_file_size 2G;

location = / {
    rewrite ^ /index.html permanent;
}

location / {
    proxy_pass http://structure.example:80;
}

location /cdn {
    proxy_pass http://content.example:80;
}

error_page   500 502 503 504  /50x.html;
location = /50x.html {
    root   /usr/share/nginx/html;
}

}

接受的答案有一个缺点:转到 example.com 会显式重定向到 example.com/index.html (即returns301 Moved permanently),这并不总是需要的。

相反,我建议在 location / 前面添加另一个指令 location = /,它仅针对根 URL 设计:

location = / {
    proxy_pass http://structure.nocms:80/index.html;
}

location / {
    proxy_pass http://structure.nocms:80;
}

上面指示 nginx 将对 example.com 的请求直接传递给 http://structure.nocms:80/index.html,同时在 [=21] 中请求任何其他 URL =]example.com/*会将请求传递给下游相应的URL。