Nginx proxy_redirect 指令

proxy_redirect 指令用于修改 后端服务器返回的 301 或 302 的 地址,看个栗子。


下面是 Nginx 配置。

server {
listen 80 default_server;

location / {
    proxy_pass http://127.0.0.1:8080;
    proxy_redirect ~^[^:]+://[^/]+/(.*) $scheme://nosa.me/category/aws/;
    }
}

用 tornado 写一个简单的后端。

import tornado.ioloop
import tornado.web

class MainHandler(tornado.web.RequestHandler):
    def get(self):
        self.set_status(301)
        self.add_header("Location", "http://nosa.me/category/web_develop/")

        application = tornado.web.Application([
            (r"/", MainHandler),
        ])

if __name__ == "__main__":
    application.listen(8080)
    tornado.ioloop.IOLoop.current().start()

测试一下,请求 Nginx 。

$ curl -i http://127.0.0.1
HTTP/1.1 301 Moved Permanently
Server: Tengine/1.5.2
Date: Wed, 27 May 2015 04:05:10 GMT
Content-Type: text/html; charset=UTF-8
Content-Length: 0
Connection: keep-alive
Location: http://nosa.me/category/aws/