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

Pil*_*ton 4 nginx nginx-location nginx-reverse-proxy

我目前正在使用URL路径的JS项目上工作。现在,如果我使用example.com/进入我的网站,则JavaScript将无法工作,因为我实际上需要example.com/index.html

我已经在使用反向代理来代理传递给两个不同的Docker容器。所以我的想法是将请求传递给example.com/index.htmlexample.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;
}

}
Run Code Online (Sandbox Code Playgroud)

我尝试过的东西:

    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;
}

}
Run Code Online (Sandbox Code Playgroud)

Vla*_*rov 10

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

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

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

location / {
    proxy_pass http://structure.nocms:80;
}
Run Code Online (Sandbox Code Playgroud)

上面指示 nginx 将请求直接传递给example.comhttp://structure.nocms:80/index.html,而请求example.com/* 中的任何其他 URL会将请求传递给下游的相应 URL。


Tar*_*ani 7

下面的配置应该适合你

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;
}

}
Run Code Online (Sandbox Code Playgroud)