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

时间:2017-09-08 10:49:53

标签: nginx nginx-location nginx-reverse-proxy

我目前正在开发一个使用url路径的JS项目。现在,如果我使用 example.com / 访问我的网站,JavaScript将无效,因为我实际上需要 example.com/index。 HTML 即可。

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

}

2 个答案:

答案 0 :(得分:6)

下面的配置应该适合你

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

}

答案 1 :(得分:4)

接受的答案有一个缺点:转到 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;
}

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