在nginx服务器中打开其他网站链接

时间:2012-11-08 06:49:39

标签: nginx

我是Nginx的新手,我使用this tutorial设置了服务器。现在,当我添加到http://www.anotherwebsite.com等其他网站的链接时,当我从我的页面点击此链接时,服务器会将我引导至http://www.mywebsite.com/http://www.anotherwebsite.com。服务器将其他链接附加到我的网站链接。我该如何改变呢。我调查了这些地方 How to redirect a url in NGINXRewrite to pretty links with nginx 但我不能让它发挥作用。任何帮助将不胜感激。感谢

server {
    listen          80;
    server_name     $hostname;
    location /static {
        alias /var/www/<app-name>/static;
    }
    error_page   404              /404.html;
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }
    location / {
        include         uwsgi_params;
        uwsgi_pass unix:/tmp/uwsgi.sock;
        uwsgi_param UWSGI_PYHOME /var/www/<app-name>/env;
        uwsgi_param UWSGI_CHDIR /var/www/<app-name>/project;
        uwsgi_param UWSGI_MODULE <project-name>.wsgi:application;
    }      
}

1 个答案:

答案 0 :(得分:2)

你没有从发布的nginx配置中进行任何重定向, 除了/ static /和/50x.html之外的所有内容都会传递给uwsgi app

因此,重定向必须在uwsgi应用程序中发生

就nginx中的重定向而言,简单的情况如下:

location /redirected-path {
  #for 302 redirect
  rewrite ^ http://anotherwebsite.example.com/path-on-other-site redirect; 

   #for 301 redirect
  # rewrite ^ http://anotherwebsite.example.com/path-on-other-site permanent;
}

(更复杂的案例涉及比^更复杂的正则表达式)

更新:

是的,所以从下面评论中链接的代码中,您真正想要做的是更改输出的html代码锚标记的href值。

这样做的正确位置是在后端代码中(即在您连接的uwsgi应用程序中)

您可以通过以下重写来完成:

 location /main {
   rewrite ^/main(.*) http://www.mysite.com$1 permanent;
 }

但是这有一个很大的缺点,就是需要额外往返服务器,然后客户端会这样做:

  1. 请求到您的服务器
  2. 重定向到其他服务器的响应
  3. 请求到其他服务器
  4. 来自其他服务器的响应
  5. 如果您在后端代码中更改它,则不再需要步骤1和2。

    除了导致潜在的(取决于连接速度和服务器负载)明显的延迟。它还会增加您的服务器负载。

    使用服务器重写执行它是一个你真正应该跳过的黑客,除非你无法访问后端代码