【问题标题】:How to redirect all incoming http request to a specific url in nginx config file?如何将所有传入的http请求重定向到nginx配置文件中的特定url?
【发布时间】:2019-04-27 18:36:12
【问题描述】:

我知道,我知道。这个问题被问了太多次,我也研究了很多。但是互联网上的每一个解决方案都把我带到了死胡同。 我想将所有传入的 http 请求重定向到特定的 url/域。 例如,如果有人在浏览器的 url-bar 中键入 - www.test.com 或只是 test.com,它应该将用户重定向到 http://test.com/home
这是我过去 3 天一直在努力实现的目标,不知道我做错了什么。
这是我的服务器块。

server {
        listen   80;
        server_name test.com;
        port_in_redirect off; 
     #  server_name_in_redirect off; 
        client_max_body_size 20M; 

 location / { 

      proxy_set_header        Host $host;
      proxy_set_header        X-Real-IP $remote_addr;
      proxy_set_header        X-Forwarded-For
      $proxy_add_x_forwarded_for;
      proxy_set_header        X-Forwarded-Proto $scheme;
      proxy_redirect off; 
      proxy_pass          http://localhost:8000/ ;
      proxy_read_timeout  90;     
      return 301 http://test.com/home;

        }

}

上面的配置给了我错误 - 当我尝试访问网站时,浏览器上的 too many redirection。同时删除了 return 语句给我 page not found 错误,并且没有将 URL 更改/重定向到 http.test.com/home

PS - 我还在同一台服务器上的 443(https) 端口上运行另一个不同的网站,并且运行良好。我正在运行一个 Spring-boot 应用程序。
非常感谢您的帮助。

【问题讨论】:

  • 你试过了吗 - location ~ ^/$ { return 301 http://test.com/home; } ?
  • 是的,我也试过了,结果浏览器出现404 Not Found 错误。

标签: http spring-boot nginx server url-redirection


【解决方案1】:

你写了太多与重定向相关的代码,这就是为什么显示这个错误。

如下更改您的服务器块。

server {
    listen   80;
    server_name test.com www.test.com;
    client_max_body_size 20M; 
    #return 301 http://test.com/home$request_uri;
}

location ~ ^/(?!home) { 
  return 301 http://test.com/home$request_uri;
}

location /home {
    root   /var/www/test.com/html/;
    index  index.html index.htm;
}

【讨论】:

  • 感谢您的回复,我尝试了您的方法,但它在每个浏览器上显示相同的错误 too many redirectsERR_TOO_MANY_REDIRECTS 。也尝试清除浏览器的缓存和 cookie。此外,粘贴此代码后,它会在 url test.com/home/home/home/home/home/home 上重定向太多次。
  • @smit 我明白了,怎么了。试试上面的代码
  • 这给了我们错误 - this site can't be reached
  • @sumit,它显示是因为在这里您只重定向到另一个位置,但没有为/home URL 提供任何数据,您需要再添加一个位置来提供数据。
  • 再次使用ERR_TOO_MANY_REDIRECTStest.com/home/home/home/home/home/home上创建网址
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-02-22
  • 1970-01-01
  • 2013-10-11
  • 2014-03-15
  • 2016-05-04
  • 2011-05-04
相关资源
最近更新 更多